tags:

views:

44

answers:

1

Hi all,

After two hours of head scratching and googling - i'm stuck!

As per the title I'm trying to return an array that is built up as the function loops through. I want to only return the array variable on the else however it will not co-operate. It simply returns as blank away from the function, however within the else I can print_r it and shows as expected. It just simply won't return the array in the $open_array variable. Any ideas (or abuse) would be greatfully appreciated!

function find_parent($number, $open = false) {
   if(isset($other_variable[$number])) {
        foreach($other_variable[$number] as $val) {
           $open[$val->id] = [$val->id;
           $open = find_parent([$val->id, $open);

        }
   }
   else {
    return $open;
   }
}

$open_array = find_parent($number);
print_r($open_array);
+1  A: 

In the "then" part, you assign to $open, but then never return that value. So you can't really expect to ever get something back, except in those cases where you enter the else part, but then it's an unchanged version.

So here's what I'd do: I'd go with a version without returning $open ever. Initialize $open before you call the function. Pass it on. Then modify it where necessary.

There's no reason really to return this $open value since you're passing it on by reference anyway, i.e. it should always be the same object which you're manipulating (and in those cases that it isn't, it's probably a bug).

This way, you can concentrate on the flow logic with your calls and returns, and be sure you always talk to the same datastructure.

update

function find_parent($number, $open = false) { 
   if(isset($other_variable[$number])) { 
        foreach($other_variable[$number] as $val) { 
           $open[$val->id] = [$val->id; 
           $open = find_parent([$val->id, $open); 
           return $open; // INSERTED
        } 
   } 
   else { 
    return $open; 
   } 
} 
Nicolas78
I understand your comment thank you :). But it still doesn't make sense to me that I can print_r($open) inside the else it prints the array as I expect it yet I can't return it?
Hayden
try returning it in the "then" part as well (see update). otherwise the value is set in the "then" part, correctly passed on to the recursive call, so it's also present in the "else" part, but once the "if" part of the previous call is returned, it's not returned.
Nicolas78
Bingo that worked a treat. Thank you!
Hayden