PHP – Pass by Reference or Pass by Value

Passing a variable by reference or by value to a function is a very useful concept for PHP programmers. Normally, when you are passing a variable to a functon, you are passing “by value” which meand the PHP procesor will make a duplicate variable to work on. When you pass a variable to a function “by reference” you passing the actual variable and all work done on that variable will be done directly on it.


<?
function pass_by_value($param) {
push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_value($ar);

foreach ($ar as $elem) {
print "
$elem";
}
?>

The code above prints 1, 2, 3. This is because the array is passed as value.


?
function pass_by_reference(&$param) {
push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_reference($ar);

foreach ($ar as $elem) {
print "
$elem";
}
?>

The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that the function (pass_by_reference) doesn’t manipulate a copy of the variable passed, but the actual variable itself.

In order to make a variable be passed by reference, it must be declared with a preceeding ampersand (&) in the function’s declaration.


About this entry