-1
<?php
$sections = ['test', 'nesto', 'fo', 'bar', ['obama', 'tito']];

function search($sections, $query){
    $found = false;

    foreach ($sections as $section){
        if ($section == $query){
            $found = true;
            var_dump($found);
            return $found;
        }

        if (is_array($section)){
            search($section, $query);
        }
    }

    var_dump($found);

    return $found;
}

if (search($sections, 'obama')){
    echo 'search item found';
}else{
    echo 'nothing found';
}

I wrote a simplified version of my problem. Basically I am trying to find a value inside an nested array. I get the following output: bool(true) bool(false) nothing found. Why does found value change from true to false. Why doesn't the function terminate when $section == $query ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mahir
  • 29
  • 4

1 Answers1

-1

Try this

$sections = ['test', 'nesto', 'fo', 'bar', ['obama', 'tito']];

function search($sections, $query){
    $found = false;

    foreach ($sections as $section){
        if ($section == $query){
            $found = true;
            var_dump($found);
            return $found;
        }

        if (is_array($section)){
            return search($section, $query); //add return here
        }
    }

    var_dump($found);

    return $found;
}

if (search($sections, 'obama')){
    echo 'search item found';
}else{
    echo 'nothing found';
}

You have to return the result of the recursive call.

Output

bool(true)
search item found

Sandbox

You were this [-] close, lol.

Also you could probably do it this way:

$found = search($section, $query);

And let the return at the end of the function catch it. Your choice. Think of it like a stack of function calls (because that is what it is). You have to return the result back up through the stack so that it can return from the first call (where your output happens).

Cheers!

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Thanks for the reply. The answer was so simple, and yet for some stupid reason i haven't really thought about that hahah. Cheers! – Mahir Oct 06 '18 at 11:19