【php手册:运算符】递增/递减运算符,手册运算符
http://php.net/manual/zh/language.operators.increment.php
递增/递减运算符
例子 名称 效果
++$a 前加 $a 的值加一,然后返回 $a。
$a++ 后加 返回 $a,然后将 $a 的值加一。
--$a 前减 $a 的值减一, 然后返回 $a。
$a-- 后减 返回 $a,然后将 $a 的值减一。
NULL递增结果为1
递增字符变量的算数运算,PHP 沿袭了 Perl 的习惯
C 中,a = 'Z'; a++; 将把 a 变成 '['('Z' 的 ASCII 值是 90,'[' 的 ASCII 值是 91);
Perl 中 $a = 'Z'; $a++; 将把 $a 变成'AA'.
Example #1 涉及字符变量的算数运算
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
echo ++$s . PHP_EOL;
}
echo '== Digits ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
?>
//a->z 9->0
字母 + 一位数字 =》 字母递增一次,数字循环递增. 如 A8 => B9 => B0
字母 + 两位以上位数字 =》 字母不变,数字循环递增. 如 A98 =》 A99 =》 A00
有趣的例子
1
$a="9D9";
var_dump(++$a); => string(3) "9E0"
var_dump(++$a); => float(10)
//识别科学计数法
2
<?php
$n = 3;
echo $n-- + --$n;
echo "<br/>";
echo $n;
?>
1. Postfix form of ++,-- operator follows the rule [ use-then-change ],
2. Prefix form (++x,--x) follows the rule [ change-then-use ].
Solution based on the rule:
Step 1:
use then change $n-- use is 3 and change is 2
Step 2.
change then use --$n change is 2 and use is 1
Step 3.
use + use = (3 + 1) = 4
3
$i++ took 8.47515535355 seconds and 2360 bytes
++$i took 7.80081486702 seconds and 2160 bytes
//前置自增比后置自增快,并且所占内存少
PHP之友评论