PHP Increment/Decrement Operators

PHPServer Side ProgrammingProgramming

Introduction

C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1. Both are unary operators as they need only one operand. These operators (++ or --) can be used in prefix or postfix manner, either as an expression or along with other operators in a more complex expression.

Syntax

$x=5;
$x=5;
$y=5;
$x++; //postfix increment
$y--; //postfix decrement

++$y; //prefix increment
--$x; //prefix decrement

When used independently, postfix and prefix increment/decrement operator behave similarly. As a result, $x++ and ++$x both increment value of $x by 1. similarly $y-- as well as --$y both decrement valaue of $y by 1

Following code shows effect of increment/decrement operator in post/prefix fashion

Example

 Live Demo

<?php
$x=5;
$y=5;
$x++; //postfix increment
$y--; //postfix decrement
echo "x = $x y = $y" . "\n";
++$y; //prefix increment
--$x; //prefix decrement
echo "x = $x y = $y" . "\n";;
?>

Output

Following result will be displayed

x = 6 y = 4
x = 5 y = 5

When used in assignment expression, postfix ++ or -- operator has lesser precedence than =. Hence $a=$x++ results in $a=$x followed by $x++. On the other hand, prefix ++/-- operators have higher precedence than =. Therefore $b=--$y is evaluated by first doing --$y and then assigning resultant $y to $b

Example

 Live Demo

<?php
$x=5;
$y=5;
$a=$x++; //postfix increment
echo "a = $a x = $x" . "\n";
$b=--$y; //prefix decrement
echo "b = $b y = $y" . "\n";
?>

Output

Following result will be displayed

a = 5 x = 6
b = 4 y = 4

Increment/ operation with ASCII character variables is also possible. Incrementation result in next character in the ASCII set. If incrementation exceeds the set, i.e. goes beyond Z, next round of ASCII set is repeated i.e. variable with value Z will be incremented to AA. Non-ASCII characters (other than A-Z, a-z and 0-9) are ignored by increment operator.

Example

 Live Demo

<?php
$var='A';
for ($i=1; $i<=3; $i++){
   echo ++$var . "\n";
}
$var1=1;
for ($i=1; $i<=3; $i++){
   echo ++$var1 . "\n";
}
?>

Output

Following result will be displayed

B
C
D
2
3
4
raja
Published on 19-Sep-2020 17:20:56
Advertisements