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

Let’s see this 2 piece of code.

<br />
&lt;?php<br />
$i=5;<br />
echo $i++;<br />
//output will be 5<br />
?&gt;<br />

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

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

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

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

%d bloggers like this: