PHP arrays are pass by value or pass by value?

According to PHP manual the array assignment is nothing but coping value.

Normally when an array is assigned to another variable it simply copies values. When an array is passed as a parameter of a function/method, it is passed by value not by reference. Lets consider following two cases:

Array as function parameter

When an array is passed to a function as parameter then it is passed as value. The parameter simply copies the array values. Any change to the parameter will not change the original array. See the code below:
$cars = array('BMW', 'Tesla', 'Audi');
function getCarList($param){
  $param[] = 'Mercedes';
}

getCarList($cars);
print_r($cars);

Output

Array ( [0] => BMW [1] => Tesla [2] => Audi )
It is also possible to pass the array as reference using reference operator in the function parameter. If the the array is passed by reference then the parameter will be linked and will point to the original array. Any change to the parameter inside the function will change the original array. See the code segment below:
$cars = array('BMW', 'Tesla', 'Audi');
function getCarList(&$param){
  $param[] = 'Mercedes';
}

getCarList($cars);
print_r($cars);

Output

Array ( [0] => BMW [1] => Tesla [2] => Audi [3] => Mercedes )


Array assignment

Normal assignment will simply copy values from one array to another array. That is way changing in one array will not effect other array. See the example below:
$cars = array('BMW', 'Tesla', 'Audi');
$latestCars   = $cars;
$latestCars[] = 'Mercedes';
echo ($cars === $latestCars) ? 'Both arrays are same' : 'Both arrays are not same';
print_r($cars);
print_r($latestCars);

In the above case both the arrays will not be same and adding new element to array $latestCars will not change the array called $car. See the output below:

Output

Both arrays are not same Array ( [0] => BMW [1] => Tesla [2] => Audi ) Array ( [0] => BMW [1] => Tesla [2] => Audi [3] => Mercedes ) But if the reference operator is used for assignment then it creates link and points to the original array. See the code snippet below:
$cars = array('BMW', 'Tesla', 'Audi');
$latestCars   = &$cars;
$latestCars[] = 'Mercedes';
echo ($cars === $latestCars) ? 'Both arrays are same' : 'Both arrays are not same';
print_r($cars);
print_r($latestCars);

In the above case both the arrays will be same cause both the arrays are symbol table aliases. So the change in $latestCars will change the array called $car. See the output below:

Output

Both arrays are same Array ( [0] => BMW [1] => Tesla [2] => Audi [3] => Mercedes ) Array ( [0] => BMW [1] => Tesla [2] => Audi [3] => Mercedes ) When But is it also possible to use reference operator for coping array.

Comments