How can you pass a variable by reference in PHP?

Write an ampersand (&) before the parameter in the function. Then the function works on the original variable, not on a copy.

Normally PHP passes arguments by value. If the function changes the value, the variable outside does not change. With a reference it does.

<?php
function add_line(&$line) {
    $line .= " and extra words added.";
}

$sample = "This is a sample line,";
add_line($sample);

echo $sample;
?>

Output:

Tutorials Class - Output Window

This is a sample line, and extra words added.

Without the &, the output would be only “This is a sample line,”. Objects are different: PHP passes the handle of an object, so a function can change its properties without any ampersand.

Note: Use references only when you really need them, because they make the code harder to follow. Often it is cleaner to return the new value from the function. See PHP Functions.

Learn more about the similar topics:
Tutorials
PHP Functions
Exercises & Assignments
Factorial program in PHP using recursive function
Write a PHP program to calculate area of rectangle
Interview Questions & Answers
What is PHP Function?
What is PHP floor() function?
How to count the number of parameters passed in a PHP function?
How can you pass a variable by reference in PHP?