0

The function aims at finding an item in a range of arrays, and then returning its key.

Problem is that the function doesn't return anything, whereas it would echo the expected result... Here is my code:

function listArray($tb, $target){
    foreach($tb as $key => $value){
        if(is_array($value)){ // current value is an array to explore
            $_SESSION['group'] = $key; // saving the key in case this array contains the searched item
            listArray($value, $target);
        }else {
            if ($target == $value) { // current value is the matching item
                return $_SESSION['group']; //Trying to return its key
                break; // I'd like to close foreach as I don't need it anymore
                }
        }
    }
}

By the way, an other little thing: I'm not used to recursive function, and I didn't find any other solution than using a session variable. But there might be a nicer way of doing it, as I don't use this session variable elsewhere...

Yako
  • 3,405
  • 9
  • 41
  • 71
  • What happens when none of the conditions you set are met? i.e. if $value isn't an array but it's also != $target. This might be the source of the problem. – Ynhockey Mar 08 '12 at 14:49
  • 1
    what's the goal of the function? – Sirko Mar 08 '12 at 14:49
  • The function aims at finding an item in a range of arrays, and then returning its key. – Yako Mar 08 '12 at 14:56

2 Answers2

2

You need a return before the recurring listArray call.

Thank about it ..

return;
break;

That break is never reached (I don't believe you can use break to exit a function in php anyway)

The second return returns from a recursive call. Let's say that this was not two separate functions:

function foon() {
   barn();
}
function barn() {
   return true;
}

foon has no return statement.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • I didn't paste my other tries. One of them was to `return` outside the `foreach`. Is this what you mean ? – Yako Mar 08 '12 at 15:02
  • You *could* do that .. you have to store the result of the `listArray` function into a variable, though. Actually you need to change your function a bit since you don't want the correct `listArray` result to be overwritten if an incorrect value comes later (I think you are trying to do that with the break). – Explosion Pills Mar 08 '12 at 16:02
  • OK, I stored the result in a variable. But I don't understand where I should return it. It doesn't work at the end of the function... `if (isset($result)){return $result;}` – Yako Mar 08 '12 at 16:54
0

I finally bypassed the problem by storing my result in a $_SESSION variable.

So, no return anymore...

$_SESSION['item'][$target] = $_SESSION['group'];
Yako
  • 3,405
  • 9
  • 41
  • 71