René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

PHP: Pass by reference vs. Pass by value

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

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

pass_by_value($ar);

foreach ($ar as $elem) {
  print "<br>$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 "<br>$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.