Reputation: 495
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
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
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
Reputation: 726
Just a guess, but maybe those statements should be else if
s? Could cause some weird recursion issues unless that's intentional.
Upvotes: 0