References

1

Sometimes you need to refer the same variable content with a different name. Consider this example:

$a = 10;
$b = $a;
$b = 20;
var_dump($a, $b); # a = 10, b = 20

In the example above $a and $b store their values independently. However you can reference the same value with PHP reference:

$a = 10;
$b = &$a;
$b = 20;
var_dump($a, $b); # a = 10, b = 10

Both $a and $b now equal to 10 because $b is not an ordinary variable but a reference to another variable.

PHP references are useful with functions. If you modify a function argument inside a function body that won't affect the value which has been passed to the function:

function plus_five($value)
{
    $value += 5;
}

$a = 15;
plus_five($a);
var_dump($a); # a = 15

That could be changed by replacing a value syntax with a reference:

# function parameter is a reference now
function plus_five(&$value)
{
    $value += 5;
}

$a = 15;
plus_five($a);
var_dump($a); # a = 20

You can also capture a variable into a function by reference:

$me = 'Sam';

# Capture by value
$say_hello = function($name) use($me)
{
    $me = 'Todd';
    # ...
};

$say_hello('Jennifer');

var_dump($me); # Prints "Sam"
$me = 'Sam';

# Capture by reference
$say_hello = function($name) use(&$me)
{
    $me = 'Todd';
    # ...
};

$say_hello('Jennifer');

var_dump($me); # Prints "Todd"

References are also useful with foreach and arrays. Compare this pair of examples:

$values = [1, 2, 3, 4, 5];

# Iterate by value
foreach($values as $value)
{
    $value *= 3;
}

var_dump($values); # Prints [1, 2, 3, 4, 5]
$values = [1, 2, 3, 4, 5];

# Iterate by reference
foreach($values as &$value)
{
    $value *= 3;
}

var_dump($values); # Prints [3, 6, 9, 12, 15]

You can also use this with associative arrays:

$wallets =
[
    'Sam'      => 120,
    'Todd'     => 150,
    'Jennifer' => 290
];

foreach($wallets as $name => &$value)
{
    $value -= 50;
}

var_dump($wallets); # Prints ['Sam' => 70, 'Todd' => 100, 'Jennifer' => 240]
Share this page:

Learning plan

The things you should know about PHP type system
The basement of PHP control flow structures you should learn before continue
It's time to create your own PHP functions
8. References
How reference the same PHP values with different names
Most common and useful PHP built-in functions
The next portion of things you should learn about PHP types
The second part of basics of PHP arrays