Description
The following code:
<?php
$arr = [1, 2, 3];
echo "first foreach\n";
foreach($arr as &$a) {
echo "{$a}\n";
}
echo "second foreach\n";
foreach($arr as $a) {
echo "{$a}\n";
}
Resulted in this output:
first foreach
1
2
3
second foreach
1
2
2
But I expected this output instead:
first foreach
1
2
3
second foreach
1
2
3
Iterating over the same array twice with foreach when the first one is by ref and the second one is by val makes the last two values of the second loop the same. It's a very particular behavior that I happened to stumble across in code today that was creating an odd issue. This is version agnostic. I tested all the way back to 5.6, so this behavior has been around for a while.
If both loops are by ref or both are by val, it behaves correctly. If the first loop is by val and second is by ref, it also behaves correctly. Only when the first is by ref and the second is by val does it misbehave.
PHP Version
PHP 8.3.10
Operating System
No response