2

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.

6
  • Because the array has three elements, I would expect the test() function to be called 3 times. (I've added this to the question) Commented Apr 14, 2023 at 9:28
  • Ah, of course. I'm blind. Commented Apr 14, 2023 at 9:29
  • My guess would be that the fact that you are using references in both cycles forces php to work with exact same array. Because of that the foreach in function resets the array's internal iterator and each step of the foreach outside of function actually starts from the start again. Commented Apr 14, 2023 at 9:35
  • FWIW, some change in PHP 7 seems to cause this: 3v4l.org/MJ6ra Commented Apr 14, 2023 at 13:24
  • A different representation of the same issue. 3v4l.org/2BIoX Assigning the input array reference from inside the nested loop seems to be a significant factor. What you assign the reference to appear irrelevant: 3v4l.org/ZWrQD Commented Apr 14, 2023 at 13:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.