PHP Operators Step By Step Tutorial - Part 10: Increment/Decrement Operator is useful for addition and reduction of principal value by applying pre- and porst principe.
The table of Increment/Decrement Operator:
| Operator |
Info |
Example |
| ++ |
Addition |
Value of b will increase before (pre-) expression $ a ++ $ b is done. 1. $b = 5; $a = ++ $b;
hence its result :
$a = 6
$b = 6
value of b will increase after (post-) expression $ a = $ b ++ is done.
2. $b = 5; $a = $b++;
hence its result :
$a = 5
$b = 6
|
| -- |
Reduction |
value of b will decrease before ( pre-) expression $ a -- $ b is done 1. $b = 5; $a = -- $b;
hence its result :
$a = 5;
$b = 5;
Value of b will increase after (post-) expression $ a = $ b -- is done.
$b = 5;
$a = $b--;
hence its result :
$a = 5;
$b = 4;
|
Pay attention to the example of using operator increment and decrement at script as following:
File name: incdec.php
<html>
<head>
<title>Using Increment/Decrement Operator</title>
</head>
<body>
<h1>Increment/Decrement Operator</h1>
<?
echo ("<h3>Increment Operator (pre-)</h3>");
$a = 7;
printf ("\$a = %d <br>", $a);
$b = ++$a;
printf ("\$a = %d <br>", $a);
printf ("\$b = %d <br>", $b);
echo ("<h3>Increment Operator (post-)</h3>");
$x = 7;
printf ("\$x = %d <br>", $x);
$y = $x++;
printf ("\$x = %d <br>", $x);
printf ("\$y = %d <br>", $y);
echo ("<h3>Decrement Operator(pre-)</h3>");
$a = 7;
printf ("\$a = %d <br>", $a);
$b = --$a;
printf ("\$a = %d <br>", $a);
printf ("\$b = %d <br>", $b);
echo ("<h3>Decrement Operator (post-)</h3>");
$x = 7;
printf ("\$x = %d <br>", $x);
$y = $x--;
printf ("\$x = %d <br>", $x);
printf ("\$y = %d <br>", $y);
?>
</body>
</html>
The result of incdec.php: