Pre and post increment - the ++ operator
Archive - Originally posted on "The Horse's Mouth" - 2009-02-03 05:16:56 - Graham EllisThe ++ (increment) operator in PHP (and Perl, and C, and Ruby) adds one to the value held in a variable and saves the result back in the same variable. But you'll see both $n++; and ++$n; in code. What is the difference?
If you write the ++ in front of the variable name, the variable is incremented before it is used for anything else in the context it is written (know ad a pre-increment), but if it is written after the variable name, the existing contents of the variable are used for anything else that's done in the content and the variable is then increments - a post increment. Look at this example:
<?php
$f = 6 + 7; # 1
$k = $f++; # 2
$m = ++$f; # 3
$g = 8 + 9;
$h = $f . $g; # 4
print "$h $k $m\n";
?>
The line #1 sets the variable $f to 13.
Line #2 sets $k to the contents of $f (13) and THEN increments $f to make it 14. A postincrement.
Line #3 increments $f and THEN stores the result (now 15) into $k. A preincrement
So the code runs like this:
Dorothy:f9php grahamellis$ php silly
1517 13 15
Dorothy:f9php grahamellis$
Some Notes
1. In C, if you use ++ on a pointer variable, it will increment it by one memory address and thus provide you with a way of incrementing through an array. If you write
int * mypointer;
...
mypointer++;
You will actually add two or four to the variable, depending on whether you are compiling with 2 byte or 4 byte integers (the latter is he default in most systems these days)
2. The -- operator (decrement) behaves in the same way
3. As good programming practise in code that you're writing for maintainance by casual or inexperienced programmers, you should consider writing the assignment and increment as two separate operations - for example, code a postincrement as:
$m = $f; $f++
4. If you want to increment by a different amount, use the += operator in any of the languages that I have mentioned so far:
$days += 5;
5. Python does NOT support the ++ operator, but it does support +=
6. You will find that most languages that we teach also support -=, *=, /=, %= ... and even more similar operations. Here's a Perl example:
$agemlimit ||=18;
Which sets $agelimit to 18 unless it already has a non-zero value, Neat, huh, but pity the newcomer!
Line #4 shows how the . operator concatenates strings in PHP ... even if the incoming variables are both integers. The type conversion is automatic.