PHP Increment Operators

Increment operators helps us to perform increment operations. If we want to increment value of a variable by 1 then we use increment operator. Increment operators are of two types:

  1. Pre-Increment operator
  2. Post-Increment Operator


Operator Function Example
++a (Pre-Increment operator) Increments self first then assigns value a=1, b=++a, value of a=2, b=2
a++ (Post-Increment operator)  Assigns value first then increments self a=1, b=a++, value of a=2, b=1

Pre-Increment Operator (++a):

To better understand the functionality of pre increment operator, lets take example.

<?php $num1=100;


echo $num1;

echo “<br>”;

echo $num2;


The output of above code would be 101,101

Here $num1 value is also incremented. Because pre-increment operator increments the value first then assigns the value.

In this case, the value of $num1 is incremented first then assigned to $num2.

Note: In the above code, you could notice echo “<br>”: This is break statement tag from HTML. This tag shifts next text to new line. With out this tag, it would have printed $num1 and $num2 value in one line. I have used break tag here, to print $num1 value in one line and $num2 value in next line.

Post-Increment Operator(a++):

To better understand the functionality of post increment operator, lets take example:




echo $num1;

echo “<br>”;

echo $num2;


The above code would output: 101,100

Here $num1 value is incremented but $num2 value is not incremented. Because post-increment operator assigns the value first then increments.

In this case, the value of $num1 that is 100 is assigned to $num2 first, then $num1 value incremented by 1.

So when you use pre-increment operator and post increment operator, you need to be careful because both type increment operator functions differently.