2

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

2
  • 1
    use pre-increment operator Commented Jun 21, 2013 at 13:45
  • 5566 is the expected output here. echo $a++ prints $a first and then increment the value while echo ++$a will increment $a first and then print it :) Commented Jun 21, 2013 at 13:45

5 Answers 5

4

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

Comments

1

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 

Comments

1

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?

Comments

1

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++; 

Comments

1

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.