Array References in PHP
In PHP, unlike other programming languages, arrays are also copied, not passed by reference.
Let's verify this:
<?php
$arr1 = [1, 2, 3, 4, 5];
$arr2 = $arr1;
$arr2[0] = '!';
var_dump($arr1); // won't change
?>
Now let's force the array to be passed by reference:
<?php
$arr1 = [1, 2, 3, 4, 5];
$arr2 = &$arr1;
$arr2[0] = '!';
var_dump($arr1); // will change
?>
Explain what the result of executing the code will be:
<?php
$arr1 = [1, 2, 3, 4, 5];
$arr2 = $arr1;
$arr2[0] = '!';
echo $arr1[0];
echo $arr2[0];
?>
Explain what the result of executing the code will be:
<?php
$arr1 = [1, 2, 3, 4, 5];
$arr2 = &$arr1;
$arr1[0]++;
echo $arr1[0];
echo $arr2[0];
?>
Explain what the result of executing the code will be:
<?php
$arr1 = [1, 2, 3, 4, 5];
$arr2 = &$arr1;
$arr1[0]++;
$arr2[0]++;
echo $arr1[0];
echo $arr2[0];
?>