References in Depth
A reference is a second name for the same value. Writing through one name changes what the other name shows.
A write through one name shows through the other
The second line links the name b to the same value as a. The write through b then prints through both names.
<?php
$a = 10;
$b = &$a;
$b = 25;
echo "a: " . $a . "\n";
echo "b: " . $b . "\n";A parameter that changes the caller variable
The bump function marks its parameter as a reference. The call adds one inside the function, and the caller variable prints the new value.
<?php
function bump(&$number) {
$number = $number + 1;
}
$count = 5;
echo "Before: " . $count . "\n";
bump($count);
echo "After: " . $count . "\n";A foreach loop that doubles an array in place
The loop walks the scores by reference and doubles each entry. The print_r output proves the array itself changed, and the unset line frees the loop name.
<?php
$scores = [1, 2, 3];
foreach ($scores as &$score) {
$score = $score * 2;
}
unset($score);
print_r($scores);Two names for one array
The second name is linked to the first array as a reference. The append through the second name prints through the first name.
<?php
$first = ["a" => 1];
$second = &$first;
$second["b"] = 2;
print_r($first);Example
<?php
$settings = ["theme" => "light", "size" => 12];
$edit = &$settings;
$edit["theme"] = "dark";
$edit["size"] = 14;
echo "Theme: " . $settings["theme"] . "\n";
echo "Size: " . $settings["size"] . "\n";Key points
- A reference links two names to one shared value.
- Writing through either name changes the shared value.
- A parameter marked as a reference changes the caller variable itself.
- A foreach loop by reference changes each entry of an array in place.
- An alias for an array shares the whole array with the first name.
In this example, the edit name is linked to the settings array as a reference. Both writes go through the edit name. The print lines read through the settings name and show the new theme and size.
Note
Unset the loop variable after a by-reference foreach loop so a later write cannot change the last entry by accident.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when a value changes through a reference?