Reputation: 1975
I was just playing around with PHP, can someone please explain to me why the code below prints out 5566 instead of 6666?
$a = 5;
$b = $a;
echo $a++ . $b++;
echo "\n";
echo $a++ . $b++;
Does it echo $a then add 1 to it? Why doesn't it echo the result?
EDIT: Another simple example for anyone viewing:
$a = 5;
$b = $a++;
echo $a++ . $b;
Produces 65
Upvotes: 2
Views: 174
Reputation: 20286
When you do postincrementation firstly the value is returned and then it is incremented by 1 that is why you get such results.
If you do preincremenation firstly value to $a is added then it is returned in that cause you will see 66 and 77
echo ++$a . ++$b;
will print 66 as you probably expected.
Notice pre incremenation/decrementaiton is faster than post that is why if you don't need to display the value firstly before incremenation/decremation use it.
Morover, if you use reference
$a = 5;
$b = &$a;
echo $a++ . $b++;
It will output 56
and
$a = 5;
$b = &$a;
echo ++$a . ++$b;
will output 77 :)
Upvotes: 1
Reputation: 66478
Because $a++ is post increment it return value and then increment the value.
try:
echo ++$a . ++$b;
echo "\n";
echo $a++ . $b++;
it's the same as
$a++;
$b++;
echo $a . $b;
echo "\n";
echo $a . $b;
$a++
$b++;
Upvotes: 1
Reputation: 15603
In Your code, IN first echo it returns the $a
's value after that it increment similar to $b.
Here is the $a++ explanation:
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
Hope this will be helpful to you to understand.
Check below questions also:
Pre-incrementation vs. post-incrementation
What's the difference between ++$i and $i++ in PHP?
Upvotes: 1
Reputation: 4268
It is a POST-INCREMENT OPERATOR
so the value is first being used(i.e. 5) and then incremented so you are getting 5566.
echo $a++ . $b++; // echo 55 and then a becomes 6 , b becomes 6
echo "\n";
echo $a++ . $b++; // echo 66
Upvotes: 1
Reputation: 13525
it should be echoing out
55
66
because when you place ++
after (suffix) then the increment is done after the statment is executed. if you want
66
66
then do
$a = 5;
$b = $a;
echo ++$a . ++$b;
echo "\n";
echo $a++ . $b++;
Upvotes: 4