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?

3
  • 1
    It increases the $var after the echo statement is executed i guess. Try doing echo ++$var; Commented Jan 14, 2012 at 15:43
  • @pinusnegra: To figure out how it works? Seems simple enough to learn from... Commented Jan 14, 2012 at 15:45
  • 1
    @pinusnegra Read first line: "I'm just trying to understand passing by reference in PHP by trying some examples found on php.net." Commented Jan 14, 2012 at 15:46

6 Answers 6

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!
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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.

Comments

0

Try echoing the actual variable:

echo $a; // 6

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

return ++$var;

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.