Why does a php array in two foreach loops lead to an infinite loop?

113 Views Asked by At

I have this PHP code:


$array = [1, 2, 3];

$counter = 0;
foreach($array as &$elem){
    test();
    $counter++;
    if($counter >= 10){
        return;
    }
}

function test(){
    global $array;
    
    foreach($array as $key => $element){
        echo $element;
        $test = &$array[$key];
    }
}

For some reason, the output of this code is 123123123123123123123123123123 and not 123123123 what I would expect. Because the array has three elements, I would expect the test() function to be called 3 times.

The foreach loop in the test function somehow resets the internal array pointer causing the outside loop to start with 1 again. Why is this?

I've already looked at How does PHP 'foreach' actually work?, which explains a great deal. But since I'm not changing the array, I don't understand the issue. Or is this a bug in PHP?

Note: This question is not a duplicate of Strange behavior of foreach when using reference: foreach ($a as &$v) { ... } because the two foreach loops are not in the same scope and the issue is not with the reference element being overwritten.

0

There are 0 best solutions below