1

I'm just trying to understand passing by reference in PHP by trying some examples found on php.net. I have one example right here found on the php website but it does not work:

function foo(&$var)
{
    return $var++;
}

$a=5;
echo foo($a); // Am I not supposed to get 6 here? but I still get 5

This is an example found here

Can anybody tell me why am I getting 5 instead of 6 for the variable $a?

user765368
  • 19,590
  • 27
  • 96
  • 167

6 Answers6

6

Your code and the example code is not the same. Is it a wonder they behave differently?

To see the behavior you expect, you have to change $var++ to ++$var.

What happens here is that while the value of $a is 6 after the function returns, the value that is returned is 5 because of how the post-increment operator ($var++) works. You can test this with:

$a=5; 
echo foo($a); // returns 5
echo $a; // but prints 6!
Jon
  • 428,835
  • 81
  • 738
  • 806
1

Because $a++ returns $a then increments by one.

To do what you are trying to do you will need to do ++$a.

http://www.php.net/manual/en/language.operators.increment.php

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
1

This is to do with the increment operator, rather than passing by reference. If you check the manual, you'll see to exhibit the behaviour you desire, you must change foo() to use pre-increment instead of post-increment, like so:

function foo(&$var)
{
    return ++$var;
}

Now:

> $a = 5;
> echo foo($a);
6
Greg K
  • 10,770
  • 10
  • 45
  • 62
0

not directly related to the question, only the subject. There does seem to be a PHP bug ...

$arr = array();
$arr["one"] = 1;
$arr["two"] = 2;
$arr["three"] = 3;

foreach ($arr as $k => &$v) {
$v += 3;
}

foreach ($arr as $k => $v) {
echo("\n".$k." => ".$v);
}

outputs:

one => 4
two => 5
three => 5

(changing '$v' to '$val' (or some other variable name other than '$v')       
in the second (i.e. last) 'foreach' will result in the expected correct
output (one => 4 two => 5 three => 6)
0

No, this works just fine. $var++ returns the value of $var, then increments the variable. So the returned value is 5, which is what you echo. The variable $a is now updated to 6 though.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

Try echoing the actual variable:

echo $a; // 6

If you increment before you return, your example will work though:

return ++$var;
Frederik Wordenskjold
  • 10,031
  • 6
  • 38
  • 57