While working on a project which checks the if Laravel models are related to each other I noticed some (weird?) pointer behavior going on with PHP. Below is a minimal example to reproduce what I found.
<?php
$arr = ['a', 'b', ['c']];
foreach($arr as &$letter) {
if (!is_array($letter)) {
$letter = [$letter];
}
}
dump($arr);
foreach($arr as $letter) {
dump($arr);
}
function dump(...$dump) {
echo '<pre>';
var_dump($dump);
echo '</pre>';
}
At first I expected the dumps in this response to all return the same data:
[ ['a'], ['b'], ['c'] ]
But that is not what happened, I got the following responses:
[ ['a'], ['b'], ['c'] ]
[ ['a'], ['b'], ['a'] ]
[ ['a'], ['b'], ['b'] ]
[ ['a'], ['b'], ['b'] ]
A running example can be found here.
Why do the pointers act this way? How can I update $letter in the first loop without having to do $arr[$key] = $letter?
Edit: As people seem to be misunderstanding why there is a second foreach loop, this is to show that the array is changing without being reassigned