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:
|++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|
To better understand the functionality of pre increment operator, lets take example.
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.
To better understand the functionality of post increment operator, lets take example:
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.