← Back to Chapters

PHP Function Arguments By Reference

? PHP Function Arguments By Reference

? Quick Overview

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.

? Syntax / Theory

To pass an argument by reference, prepend an ampersand & to the parameter name in the function definition.

? View Code Example
// 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++;
}

? Code Example 1: Function Modifies Original Variable

? View Code Example
// 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;
?>

? Code Example 2: Swapping Values Using References

Passing by reference is highly useful for algorithms like swapping values where multiple variables need to be updated simultaneously.

? View Code Example
// 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";
?>

? Conceptual Visualization

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.

✅ Tips & Best Practices

  • Intentional Use: Use references only when you explicitly need the function to change the input variable.
  • Avoid Side Effects: Be careful, as references can make code harder to debug if variables change unexpectedly.
  • Performance: For large objects or arrays, references can sometimes save memory, but modern PHP (7+) handles this efficiently via "Copy-on-Write" regardless.

? Try It Yourself / Practice Tasks

  • Create a function that multiplies a number by 3 using a reference parameter.
  • Write a function that accepts an array by reference and appends a "Success" string to every element.
  • Try to swap three variables (A to B, B to C, C to A) using references.