Funny PHP #2 – Self-sum operation inside another operation

Let’s see this 2 piece of code.

<?php
$i=5;
echo $i++;
//output will be 5
?>
<?php
$i=5;
echo ++$i;
//output will be 6
?>

First one will display 5, second one will display 6. Why?
Just because when you print(or echo) $i++, it will first print $i, then provide $i=$i+1 operation.
But with ++$i; it is different, as ++ comes first and happens before print output.

More difficult example

<?php
$i = 10;
$j = $i++ - 1;
echo $i.' and '.$j;
//output will be '11 and 9', not '11 and 10'.
// Because $i++ - 1; means $i-1, then $i++;
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.