Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the "&" operator work in a PHP function?

Tags:

php

Please see this code:

function addCounter(&$userInfoArray) {
    $userInfoArray['counter']++;
    return $userInfoArray['counter'];
}

$userInfoArray = array('id' => 'foo', 'name' => 'fooName', 'counter' => 10);
$nowCounter = addCounter($userInfoArray);

echo($userInfoArray['counter']);

This will show 11.

But! If you remove "&"operator in the function parameter, the result will be 10.

What's going on?

like image 558
Deckard Avatar asked Oct 18 '10 08:10

Deckard


3 Answers

The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.

Just look at this minimal example:

<?php
function foo($a) { $a++; }
function bar(&$a) { $a++; }

$x = 1;
foo($x);
echo "$x\n";    
bar($x);
echo "$x\n";
?>

Here, the output is:

1
2

– the call to foo didn’t modify $x. The call to bar, on the other hand, did.

like image 84
Konrad Rudolph Avatar answered Nov 14 '22 16:11

Konrad Rudolph


Here the & character means that the variable is passed by reference, instead of by value. The difference between the two is that if you pass by reference, any changes made to the variable are made to the original also.

function do_a_thing_v ($a) {
    $a = $a + 1;
}
$x = 5;
do_a_thing_v($x);
echo $x; // echoes 5

function do_a_thing_r (&$a) {
    $a = $a + 1;
}
$x = 5;
do_a_thing_v($x);
echo $x; // echoes 6
like image 22
Hammerite Avatar answered Nov 14 '22 15:11

Hammerite


When using the ampersand prior to a variable in a function call, it associates with the original variable itself. With that, the code you posted is saying that it will add 1 to the counter of the original array. Without the ampersand, it takes a copy of the data and adds to it, then returns the new counter of 11. The old array still remains intact at 10 and the new counter variable returned turns into 11.

http://www.phpreferencebook.com/samples/php-pass-by-reference/

is a good example.

like image 2
pyr0 Avatar answered Nov 14 '22 15:11

pyr0