user784446
user784446

Reputation: 495

PHP array loop not breaking

For some reason, using the following means to loop an array resists its break statements and continues to loop recursively to the utmost last element of the array

function loop($target, $array) {
  if($this) {
    if(!isset($GLOBALS["loop"])) {
      $GLOBALS["loop"]+=1;
      $GLOBALS["arrayCount"] = count($array, COUNT_RECURSIVE);
    }
  }
  $keys = array_keys($array);
  $values = array_values($array);
  for($i=0;$i<count($array);$i++) {
    $GLOBALS["iteration"]+=1;
    if($keys[$i] === $target) {
      print "Found $target.<br>";
      break;
    }
    if(is_array($array[$i])) {
      loop($target, $array[$i]);
    }
    if($values[$i] === $target) {
      print "Found $target.<br>";
      break;
    }
    if($GLOBALS["iteration"] >= $GLOBALS["arrayCount"]) {
      print "Looped array.<br>";
      break;
    }
}

Upvotes: -1

Views: 237

Answers (3)

Removed
Removed

Reputation: 1

That's a rather strange loop you have there. You can avoid writing your own recursion using built-in types; I think this is what you're trying to do:

<? //PHP 5.4+

$loop = static function($target, array $array){
    $query = $array;
    $query = new \RecursiveArrayIterator($query);
    $query = new \RecursiveIteratorIterator(
        $query, 
        \RecursiveIteratorIterator::SELF_FIRST
    );
    foreach($query as $key => $value){
        if ($key === $target){
            return "Found $target (key)";
        } elseif ($value === $target){
            return "Found $target (value)";
        }
    }
};

$testData = [
 'key1' => 'value1',       
 'key2' => 'value2',
 'key3' => [
     'key4' => 'value4',
 ],      
];

echo
    $loop('key2', $testData), '<br/>',
    $loop('key3', $testData), '<br/>',
    $loop('key4', $testData), '<br/>',
    $loop('value4', $testData), '<br/>'
;
/*
Found key2 (key)
Found key3 (key)
Found key4 (key)
Found value4 (value)
 */
?>

Upvotes: 0

g13n
g13n

Reputation: 3246

I actually found the issue ...

The following code:

if(is_array($array[$i])) {
  loop($target, $array);
}

should be:

if(is_array($array[$i])) {
  loop($target, $array[$i]);
}

Upvotes: 1

jmosesman
jmosesman

Reputation: 726

Just a guess, but maybe those statements should be else ifs? Could cause some weird recursion issues unless that's intentional.

Upvotes: 0

Related Questions