PHP Decrement operators helps to perform decrement operations. If we want to decrement value of a variable by 1 then we use decrement operator.
There are two types of decrement operators:
|–a (Pre-Decrement operator)||Decrements self first then assigns value||a=1, b=–a, value of a=0, b=0|
|a– (Post-Decrement operator)||Assigns value first then decrements self||a=1, b=a–, value of a=0, b=1|
To better understand the functionality of pre decrement operator, lets take example.
The output of above code would be 99,99
Here $num1 value is also decremented. Because pre-decrement operator decrements the value first then assigns the value.
In this case, the value of $num1 is decremented 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 decrement operator, lets take example:
The above code would output: 99,100
Here $num1 value is decremented but $num2 value is not decremented. Because post-decrement operator assigns the value first then decrements.
In this case, the value of $num1 that is 100 is assigned to $num2 first, then $num1 value decremented by 1.
So when you use pre-decrement operator and post decrement operator, you need to be careful because both type decrement operator functions differently.