How can you pass a variable by reference in PHP?

By using an ampersand (&) sign in-front of the variable, we can pass the variable by reference.

Why or when to use variable by reference ?

When PHP function arguments are passed by value, and value is changed within function, it does not change variable value outside the function. To allow a function to modify its argument value outside the function, they must be passed by reference.


function add_line(&$line)
    $line.= 'and extra words added.';
$sample_line= 'This is a sample line, ';
echo $sample_line;    // outputs 'This is a sample line,  and extra words added.'

If we do not use value by reference (&), then the output will be: ‘This is a sample line,’

Learn more about the similar topics:
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.