PHP functions: Pass by Reference versus Pass By Value

To illustrate the difference between Pass by Reference and Pass by Value in a PHP function, we will use a simple program. Notice the two functions in the following programs changeToUpperCase() and updateArrayToUpperCase(). On closer look, you will find that the function definitions of both are same.

<?php

function changeToUpperCase($stringArray) {
    for($i=0 ; $i < sizeof($stringArray); $i++) {
        $stringArray[$i] = strtoupper($stringArray[$i]);
    }
}

function updateArrayToUpperCase(&$stringArray) {
    for($i=0 ; $i < sizeof($stringArray); $i++) {
        $stringArray[$i] = strtoupper($stringArray[$i]);
    }
}

$days = array("Sunday", "Monday", "Tuesday", "Wednesday",
 "Thursday", "Friday", "Saturday");

echo "Before calling any functionsn";
var_dump($days);

changeToUpperCase($days);
echo "After calling changeToUpperCase()n";
var_dump($days);

updateArrayToUpperCase($days);
echo "After calling updateArrayToUpperCase()n";
var_dump($days);


?>

The output

Before calling any functions
array(7) {
  [0]=>
  string(6) "Sunday"
  [1]=>
  string(6) "Monday"
  [2]=>
  string(7) "Tuesday"
  [3]=>
  string(9) "Wednesday"
  [4]=>
  string(8) "Thursday"
  [5]=>
  string(6) "Friday"
  [6]=>
  string(8) "Saturday"
}
After calling changeToUpperCase()
array(7) {
  [0]=>
  string(6) "Sunday"
  [1]=>
  string(6) "Monday"
  [2]=>
  string(7) "Tuesday"
  [3]=>
  string(9) "Wednesday"
  [4]=>
  string(8) "Thursday"
  [5]=>
  string(6) "Friday"
  [6]=>
  string(8) "Saturday"
}
After calling updateArrayToUpperCase()
array(7) {
  [0]=>
  string(6) "SUNDAY"
  [1]=>
  string(6) "MONDAY"
  [2]=>
  string(7) "TUESDAY"
  [3]=>
  string(9) "WEDNESDAY"
  [4]=>
  string(8) "THURSDAY"
  [5]=>
  string(6) "FRIDAY"
  [6]=>
  string(8) "SATURDAY"
}

As mentioned earlier, the function definitions of both are same. Even the parameters used to call the function are the same.

changeToUpperCase($days);
updateArrayToUpperCase($days);

What makes the difference is the way by which the function arguments are written.

function changeToUpperCase($stringArray) 
function updateArrayToUpperCase(&$stringArray)

If you notice, in the second case, there is an extra parameter & with the function argument. When & is used, it signifies Pass by Reference. It means that the original parameter must not be copied to a new variable. The parameter is referred inside the function by the reference. It means that any change made in the function to a parameter passed by reference, the change can be reflected in the caller function. Hence the difference in the ouptut.