Skip to content
Advertisement

return result of foreach loop(s)

I have the some code which looks something like this (I’ve simplified it):

function process_something($a){
    foreach($a as $b){
        // Some logic here
        return $something;
    }
}
$input=[]; // An array of some kind
echo process_something($input);

I expect that final line to echo what the loops have returned but I get nothing. Maybe the above code will not work. I just put it in for illustration. I have a lot of nested loops working together to return various things.

If I have the loops echo data out, it works. However, I need this function to just return the end result to me for further processing, rather than echoing out to the user.

How do I proceed?

Advertisement

Answer

In this case this loop will only run once, because return jumps out of a function on the first occurrence.

It should be more like:

function process_something($a){
    foreach($a as $b){
        $something = 'Some math or other logic here';
    }
    return $something;
}
$input=[]; // An array of some kind
echo process_something($input);

Please post your code, we will try to figure out what’s wrong with it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement