PHP Decrement Operators

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:

  1. Pre-Decrement Operator (–a)
  2. Post-Decrement Operator (a–)
Operator Function Example
–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

Pre-Decrement Operator (–a):

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

<?php $num1=100;

$num2=- -$num1;

echo $num1;

echo “<br>”;

echo $num2;

?>

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.

Post-Decrement Operator(a–):

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

<?php

$num1=100;

$num2=$num1- -;

echo $num1;

echo “<br>”;

echo $num2;

?>

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.