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.

Anorionil
  • 505
  • 2
  • 7
  • 17
  • Because the array has three elements, I would expect the test() function to be called 3 times. (I've added this to the question) – Anorionil Apr 14 '23 at 09:28
  • Ah, of course. I'm blind. – Sergio Tulentsev Apr 14 '23 at 09: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. – Michal Hynčica Apr 14 '23 at 09:35
  • FWIW, some change in PHP 7 seems to cause this: https://3v4l.org/MJ6ra – deceze Apr 14 '23 at 13:24
  • A different representation of the same issue. https://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: https://3v4l.org/ZWrQD – mickmackusa Apr 14 '23 at 13:52
  • Simpler reproduction again: https://3v4l.org/7YANZ @deceze – mickmackusa Apr 14 '23 at 14:03

0 Answers0