Skip to content

How to Pass Arrays by Reference to Functions

Don't be fooled by the variable assignment, it does act like an object and pass by reference like following:

<?php
$arr1 = array('Apple', 'Banana');
$arr2 = $arr1;
var_dump($arr2);
?>

The output is:

array (size=2)
  0 => string 'Apple' (length=5)
  1 => string 'Banana' (length=6)

It do pass by reference. But if you pass the array to a function, it's another story, it will just copy the value to proceed by nautre:

<?php
function test_array($aug) {
$aug[] = 'Cherry';
}

$arr1 = array('Apple', 'Banana');
test_array($arr1);
var_dump($arr1);
?>

The output is still:

array (size=2)
  0 => string 'Apple' (length=5)
  1 => string 'Banana' (length=6)

If you insist to pass by reference, a simple "&" symbol should be added in front of the argument in the function declaration.

<?php
function test_array(&$aug) {
$aug[] = 'Cherry';
}

$arr1 = array('Apple', 'Banana');
test_array($arr1);
var_dump($arr1);
?>

The output is:

array (size=3)
  0 => string 'Apple' (length=5)
  1 => string 'Banana' (length=6)
  2 => string 'Cherry' (length=6)

It's a very convenient tip for PHP developers.

Leave a Reply

Your email address will not be published. Required fields are marked *