Skip to content

PHP Tutorial Variables and Constants

References: Assign by Reference

Lesson 24 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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 &.

index.php
PHP
<?php
$a = 5;
$b = &$a;   // $b is another name for $a

$b = 99;

echo "a is $a, b is $b";
Output
OUTPUT
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.

index.php
PHP
<?php
function addTax(float &$price): void
{
    $price = $price * 1.18;
}

$total = 100.0;
addTax($total);

echo $total;
Output
OUTPUT
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.

index.php
PHP
<?php
$prices = [10, 20, 30];

foreach ($prices as &$price) {
    $price = $price * 2;
}
unset($price); // important: break the reference

print_r($prices);
Output
OUTPUT
Array
(
    [0] => 20
    [1] => 40
    [2] => 60
)
dangerous
Always unset a foreach reference
After the loop, $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.
info
Prefer returning values
References make code harder to follow, because a change can happen far away from where you look. In modern PHP, it is usually clearer to return a new value from a function, like $total = addTax($total);.