Vincent
Vincent

Reputation: 117

Break is not working properly after return true;

The return true; is not ending the current function loop! This is so basic but I don't find why break is not working!

I try this piece of code:

function findKey($array, $keySearch) {
foreach ($array as $key => $item){
    echo "$key == $keySearch";
    if ("$key" == "$keySearch"){
        echo 'yes, it exists';
        return true;
    }
    else 
    {
        if (is_array($item))
            findKey($item, $keySearch);
    }
}
return false;
}

The return true; never break as it let it go after the yes, it exists is echoed!

Solved

The code itself from an accepted solution here was wrong. It has been corrected. Also, below you will find the right answer.

Upvotes: 0

Views: 182

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

You've jumped to a conclusion. In fact, your return true is assuredly ending the function immediately (including breaking out of the loop), but it only ends the current invocation of the function. Your solution is recursive, and has a bug in the else clause, whereby the result of a recursive call to findKey is completely ignored. As such, whatever happens inside that invocation has no effect.

You're seeing the echo from your outer function call.

I imagine that what you really intended to write was this:

function findKey($array, $keySearch)
{
   foreach ($array as $key => $item) {
      echo "$key == $keySearch";
      if ($key == $keySearch) {
         echo 'yes, it exists';
         return true;
      }
      else {
         if (is_array($item) && findKey($item, $keySearch))
            return true;
      }
   }

   return false;
}

I have made the same change to the original answer that you'd found.

Upvotes: 2

Related Questions