Difference between post-increment and pre-increment in php

by Sam  

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++)


$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 *

Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote