I ran into a weird issue and could reproduce it with this snippet:
<?php
$arr = [];
for($i = 0; $i <= 3; $i++) {
$arr[] = [
$i
];
}
foreach ($arr as &$item) {
$item[] = $item[0];
}
foreach ($arr as $item) {
print_r($item);
}
It is outputting (notice the last element had been replaced with a copy of its previous one):
Array
(
[0] => 0
[1] => 0
)
Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
[1] => 2
)
Array
(
[0] => 2
[1] => 2
)
However, here's the expected result:
Array
(
[0] => 0
[1] => 0
)
Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
[1] => 2
)
Array
(
[0] => 3
[1] => 3
)
If I use array_map
instead of the first foreach
, it works:
<?php
$arr = [];
for($i = 0; $i <= 3; $i++) {
$arr[] = [
$i
];
}
$arr = array_map(function ($item) {
$item[] = $item[0];
return $item;
}, $arr);
foreach ($arr as $item) {
print_r($item);
}
Tested under PHP 8.0.0.
What could be causing this difference? Is there something about array pointers I'm missing?