By default, PHP function arguments are passed by value (a copy is made). Passing arguments by reference allows a function to directly modify the original variable by passing its memory address instead of its value.
To pass an argument by reference, prepend an ampersand & to the parameter name in the function definition.
// The & symbol tells PHP to point to the original variable memory address
function increment(&$value) {
// This operation modifies the actual variable outside the function
$value++;
}
// Define a function that accepts a reference
<?php
function addFive(&$num) {
// The original variable is updated by adding 5
$num += 5;
}
// Initialize the original variable
$value = 10;
// Call function: no & needed in the call, only in definition
addFive($value);
// Output will be 15 because the original $value was changed
echo $value;
?>
Passing by reference is highly useful for algorithms like swapping values where multiple variables need to be updated simultaneously.
// Swap two variables directly in their memory locations
<?php
function swap(&$a, &$b) {
// Store first value in a temporary container
$temp = $a;
// Overwrite first variable with the second's value
$a = $b;
// Overwrite second variable with the stored temporary value
$b = $temp;
}
// Set initial variables
$x = 5;
$y = 10;
// Execute the swap
swap($x, $y);
// Displays: x = 10, y = 5
echo "x = $x, y = $y";
?>
When you pass by reference, both the internal function parameter and the external variable name "point" to the same box of data. If the function changes the data in the box, the external name sees the change instantly.