phpoperatorsincrement

Facing an issue with Increment operator in PHP


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?


Solution

  • 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 incremented