Experiments in PHP 7.1 (docker image nanoninja/php-fpm:7.1)
In next piece of code everything clear:
$arr1 = [1, 2, 3];
foreach ($arr1 as &$value) {
$value *= 2;
}
We have array $arr1
and multiply all values by 2. Result:
array(3) {
[0]=>
int(2)
[1]=>
int(4)
[2]=>
&int(6)
}
But what happens in this statement:
$arr1 = [1, 2, 3];
foreach ($arr2 = $arr1 as &$value) {
$value *= 2;
}
Result of both arrays $arr1
and $arr2
will unchangeable:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Why is it happens? I know that in PHP > 7 foreach
works with copy of array but with copy of which array it works in this case $arr1
or $arr2
. And why &
don't work?