|
|
Incrementing/Decrementing Operators in PHP
|
Tutorials » Php »
|
Topic |
What are the Incrementing/Decrementing Operators ?
|
|
Explanation |
|
PHP supports pre/post increment and decrement operators. The following table lists all the operators
| Example |
Name |
Effect |
| ++$a |
Pre-increment |
Increments $a by one, then returns $a. |
| $a++ |
Post-increment |
Returns $a, then increments $a by one. |
| --$a |
Pre-decrement |
Decrements $a by one, then returns $a. |
| $a-- |
Post-decrement |
Returns $a, then decrements $a by one. |
Post Increment/Decrement Operators
Example:
<?php
$a = 5;
//Post Increment
echo "Value of a: " . $a++ ."<br />\n";
echo "Value of a post incremented: " . $a . "<br />\n";
//Post Decrement
$a = 5;
echo "Value of a: " . $a-- . "<br />\n";
echo "Value of a post decremented: " . $a . "<br />\n";
?>
Result:
Value of a: 5
Value of a post incremented: 6
Value of a: 5
Value of a post decremented: 4
In the above example, when the post increment or decrement operator is called
it returns the same value, after that it increments or decrements the value.
Pre Increment/Decrement Operators
Example:
<?php
Pre Increment
$a = 5;
echo "Pre incremented value: " .++$a . "<br />\n";
echo "Value is same: " .$a . "<br />\n";
Pre Decrement
$a = 5;
echo "Pre decremented value: ".--$a ."<br />\n";
echo "Value is same: ".$a ."<br />\n";
?>
Result:
Pre incremented value: 6
Value is same: 6
Pre decremented value: 4
Value is same: 4
In the above example, when the pre increment or decrement operator is called it returns decremented or
incremented value first.
|
|
A Note |
Learn PHP programming language tutorial with simple and neat example. Hope you enjoy this free tutorial.
Do give us your valuable feedback and suggestions on this online tutorial. This is a Copyright Content.
|
|
|
|