PHP & Ampersand: Passing by Reference
$a = 1;
$b = &$a; // $b references the same value as $a, currently 1
$b = $b + 1; // 1 is added to $b, which effects $a the same way
echo "OUTPUT: b is equal to $b, and a is equal to $a";
OUTPUT: b is equal to 2, and a is equal to 2
function add(&$var){ $var++; } // The & is before the argument $var
$a = 1;
echo "a is $a";
$b = 10;
echo "b is $b";
add($a);
echo "a is $a";
add($b);
echo "OUTPUT: a is $a, and b is $b"; // Note: $a and $b are NOT referenced
a is 1
b is 10
ADD[a], a is 2
OUTPUT: a is 2
ADD[b], b is 11
OUTPUT: a is 2, and b is 11
$array = array(1,2,3,4);
foreach ($array as &$value){ $value = $value + 10; }
unset ($value); // Must be included, $value remains after foreach loop
print_r($array);
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
)
https://www.phpreferencebook.com/samples/php-pass-by-reference/