Normally, $b = $a copies the value. With a reference, both names point to the same value, so a change through one name shows up in the other.
You create a reference with &.
<?php
$a = 5;
$b = &$a; // $b is another name for $a
$b = 99;
echo "a is $a, b is $b";
a is 99, b is 99
Think of it as two name tags on one box.
Where references are useful
The most common use is a function that must change the caller’s variable.
<?php
function addTax(float &$price): void
{
$price = $price * 1.18;
}
$total = 100.0;
addTax($total);
echo $total;
118
Without the &, the function would change only its own copy. You will see this again in Passing by Reference.
References in foreach
You can change array items while looping by using &$item.
<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
$price = $price * 2;
}
unset($price); // important: break the reference
print_r($prices);
Array
(
[0] => 20
[1] => 40
[2] => 60
)
Always unset a foreach reference
$price is still a reference to the last array item. If you reuse that variable name later, you can overwrite the last item by accident. unset($price) removes the link.Prefer returning values
$total = addTax($total);.