1

I am facing an unexpected issue with the increment operator in PHP. Please take a look at the given two programs:

1st Program:

<?php
  $a=5;
  $a++;
  echo $a;
?> 

it prints 6, which I clearly understood that what was happened, it just incremented the value with 1.

2nd Program:

<?php
  $a=5;
  $b = $a++;     // just assigned incremented value to a new variable b.
  echo $b;
?>

it prints 5.

Now here is the confusion, I just assigned the incremented value to the variable, so I should print 6 - why it is printing 5?

halfer
  • 19,824
  • 17
  • 99
  • 186
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88
  • 1
    Possible duplicate of [Reference - What does this symbol mean in PHP?](https://stackoverflow.com/q/3737139/6521116) – LF00 May 24 '17 at 07:34
  • In this second scenario $a value not incremening,it will treated as $a is assigning to $b. So value is 5 only. – RaMeSh May 24 '17 at 07:34
  • `$a++`, use the expression value first then auto increment. while `++$a` auto increment first then use the expression value. – LF00 May 24 '17 at 07:36
  • Please read about the Post-increment operator [here](http://php.net/manual/en/language.operators.increment.php). – Álvaro González May 24 '17 at 07:36
  • @RaMeSh yes you are right, but why did it happen, it should also incremented the value. I know there is something i am not getting, i am just trying to know what's that. – Amrinder Singh May 24 '17 at 07:36
  • @Insomania How do you know it didn't increment `$a`? You're printing `$b`. – Álvaro González May 24 '17 at 07:38

1 Answers1

1

You are getting 5 because in postfix operator first it will assign the value to $b after that their value will be incremented. SO first $a is assigning to $b after that $a value will increamented

Akhilesh Jha
  • 168
  • 2
  • 11