Incrementing / Decrementing Operators
(递增/递减运算符)
++
increment operator
(++
增量运算符)
--
decrement operator
(--
递减运算符)
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.
These can go before or after the variable.
(这些可以在变量之前或之后。)
If put before the variable, the increment/decrement operation is done to the variable first then the result is returned.
(如果变量之前说,该递增/递减操作完成的第一变量,则返回的结果。)
If put after the variable, the variable is first returned, then the increment/decrement operation is done. (如果将变量放在变量之后,则首先返回变量,然后执行增量/减量操作。)
For example:
(例如:)
$apples = 10;
for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.
";
}
Live example
(现场例子)
In the case above ++$i
is used, since it is faster.
(在上面的情况下使用++$i
,因为它速度更快。)
$i++
would have the same results. ($i++
将具有相同的结果。)
Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result.
(预增量要快一点,因为它实际上是递增变量,然后“返回”结果。)
Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's. (后增量创建一个特殊变量,在其中复制第一个变量的值,只有在使用第一个变量之后,才将其值替换为第二个变量。)
However, you must use $apples--
, since first, you want to display the current number of apples, and then you want to subtract one from it.
(但是,必须使用$apples--
,因为首先要显示当前的苹果数, 然后再从中减去一个。)
You can also increment letters in PHP:
(您还可以在PHP中递增字母:)
$i = "a";
while ($i < "c") {
echo $i++;
}
Once z
is reached aa
is next, and so on.
(一旦到达z
则下一个是aa
,依此类推。)
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (az and AZ) are supported.
(请注意,字符变量可以递增但不能递减,即使如此,仅支持纯ASCII字符(az和AZ)。)
Stack Overflow Posts:
(堆栈溢出帖子:)