learn php script Headline Animator

jeudi 8 janvier 2009

Incrementing/Decrementing Operators

Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

????: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

???? 15-6. Increment/decrement 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.

Here's a simple example script:

echo "

Postincrement

"
;
$a = 5;
echo
"Should be 5: " . $a++ . "
\n"
;
echo
"Should be 6: " . $a . "
\n"
;

echo
"

Preincrement

"
;
$a = 5;
echo
"Should be 6: " . ++$a . "
\n"
;
echo
"Should be 6: " . $a . "
\n"
;

echo
"

Postdecrement

"
;
$a = 5;
echo
"Should be 5: " . $a-- . "
\n"
;
echo
"Should be 4: " . $a . "
\n"
;

echo
"

Predecrement

"
;
$a = 5;
echo
"Should be 4: " . --$a . "
\n"
;
echo
"Should be 4: " . $a . "
\n"
;
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented.

????? 15-4. Arithmetic Operations on Character Variables

$i = 'W';
for (
$n=0; $n<6; $n++) {
echo ++
$i . "\n";
}
?>

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.

Aucun commentaire:

Enregistrer un commentaire