
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Increment and Decrement Operators
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
<?php $x=5; $y=5; $x++; //postfix increment $y--; //postfix decrement echo "x = $x y = $y" . "
"; ++$y; //prefix increment --$x; //prefix decrement echo "x = $x y = $y" . "
";; ?>
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
<?php $x=5; $y=5; $a=$x++; //postfix increment echo "a = $a x = $x" . "
"; $b=--$y; //prefix decrement echo "b = $b y = $y" . "
"; ?>
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
<?php $var='A'; for ($i=1; $i<=3; $i++){ echo ++$var . "
"; } $var1=1; for ($i=1; $i<=3; $i++){ echo ++$var1 . "
"; } ?>
Output
Following result will be displayed
B C D 2 3 4