PHP Increment Primer

PHP Increment Primer

With PHP, there are many ways to increase or decrease an integer with increments. Although the concept is rather simple, the truth is that not all incrementing behaves the same way. At times, a value can be added instantly, while at other times it only takes place the next time an integer is used. Often, increments are used in loops to add to an existing value each time the loop iterates.

For example, the simple statement 'echo ++$number' automatically prints the new number of $number. But, 'echo $number++' will not print the new number. In the second case, it will only print the updated number the next time the $number variable is used. A simple way to remember this is 'increments before update right away' while 'increments after update after.

Below are a simple couple of examples which show the updates before and after.

If you find this forgettful, you may want to always create the increment without printing its value. This way, you will always get the updated value when you want to use the variable.

Example

 <?php  
$a = 1; 
echo ++$a ." - " . $a;  
echo "</br/>";  
$b = 2; 
echo --$b ." - " . $b;  
echo "<br/>";  
$a = 1; 
echo $a++ ." - " . $a;  
echo "</br/><br/>";  
$b = 2; 
echo $b-- ." - " . $b; ?>

Browser Output

Obviously, the lines which match are updated right away while those that do not only happen the next time the variable is used.

2 - 2
1 - 1

1 - 2
2 - 1


Other Ways To Increment

Asides from the methods shown above, you can create a variable and just add or decrease a desired number to its existing value. The example below show a simple loop that adds 1 to the variable each time it loops and a second loop that adds 2. The first loop runs 6 times; once each for 0,1,2,3,4,5.

The second loop only loops 3 times because after the first loop $i =2, after the second loop $i = 4 and after the third loop $i = 6. Both loops have a final value of 6.

 for($i = 0; $i <=5; $i++){  
}  
echo $i; //outputs 6    
for($i = 0; $i <=5; $i++){ $i = $i + 1; }  
echo $i; //outputs 6