Difference between post-increment and pre-increment in php

We used encounter and use increment while doing our php script. But sometimes, we forget how these two increments differ.

$x++; //post-increment
++$x; //pre-increment

The table below will describe the difference between the two:

Name Operator Description
Post-increment $x++ Increments $x by one, then returns $x
Pre-increment ++$x Returns $x, then increments $x by one

Examples (Post-increment vs Pre-increment)

Alright! so, we’ll try to differentiate the two by providing an example. Please see the code below:

Post-increment (x++)


<?php

$post = 5;
$p = $post++;

/* What happens here is that:
$p = $post;
$post = $post + 1;
*/

echo $p; //returns 5
echo '<br>';
echo $post; //returns 6
?>

Pre-increment (++x)


$pre = 5;
$p = ++$pre;

/* What happens here is that:
$pre = $pre + 1;
$p = $pre;
*/

echo $p; //returns 6
echo '<br>';
echo $pre; //returns 6

Leave a Reply

Your email address will not be published. Required fields are marked *