2015-09-28 41 views
-1

自減運算符在檢查PHP頁面,我發現下面的代碼:兩個版本的PHP

for ($n=10; $n>0; --$n) { 
    //foo; 
} 

一個爲什麼會把遞減運算符變過嗎?

+2

因爲_prefix_運算符。 – user5173426

+9

[參考 - 這個符號在PHP中意味着什麼?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) –

回答

4

--$x$x--是不同的操作符。他們都將變量減1,但他們返回不同的事情。

  • --$x:這樣可以減少$x,並返回其值:

    $y = --$x; 
    // Is equivalent to 
    // $x = $x-1; 
    // $y = $x; 
    
  • $x--:這樣可以減少$x,並返回其原來

    $y = $x--; 
    // Is equivalent to 
    // $y = $x; 
    // $x = $x - 1; 
    

for,循環它應該沒有區別。該值仍在遞減。

+0

謝謝你!我以前沒見過這個。 –

+0

不客氣:-) –

5

PHP支持C風格的前-和後-增量和減量運算符。

注意:遞增/遞減運算符隻影響數字和字符串。數組,對象和資源不受影響。遞減 NULL值也沒有效果,但是遞增結果1.

++$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. 

爲例:

<?php 
echo "<h3>Postincrement</h3>"; 
$a = 5; 
echo "Should be 5: " . $a++ . "<br />\n"; 
echo "Should be 6: " . $a . "<br />\n"; 

echo "<h3>Preincrement</h3>"; 
$a = 5; 
echo "Should be 6: " . ++$a . "<br />\n"; 
echo "Should be 6: " . $a . "<br />\n"; 

echo "<h3>Postdecrement</h3>"; 
$a = 5; 
echo "Should be 5: " . $a-- . "<br />\n"; 
echo "Should be 4: " . $a . "<br />\n"; 

echo "<h3>Predecrement</h3>"; 
$a = 5; 
echo "Should be 4: " . --$a . "<br />\n"; 
echo "Should be 4: " . $a . "<br />\n"; 
?> 

PHP Manual: Incrementing/Decrementing Operators

編輯:

for ($n=10; $n>0; --$n) { 
    echo "Iterating:" . $n . "<br>"; 
} 

OUTPUT:

Iterating:10 
Iterating:9 
Iterating:8 
Iterating:7 
Iterating:6 
Iterating:5 
Iterating:4 
Iterating:3 
Iterating:2 
Iterating:1 

在你的榜樣,第一個迭代將有$n = 10作爲部分--$n在for循環結束時執行。

+2

N.B.它仍然以$ n = 10開始,因爲for循環元素的第三部分(遞減)在循環結尾 –

+0

@MarkBaker Ahh,craps處執行。讓我解決這個問題。 – user5173426

+1

帽子@HawasKaPujaari。你有很多耐心。 –

0

他們略有不同...和它的表現的事情;嘗試類似

<?php 
for($i=0;$i<100000000;++$i){ 
    //heating up the cpu (if it uses some power saving feature or whatever) 
} 
$i=0; 
$PreIncrementStart=microtime(true); 
for($i=0;$i<100000000;++$i){ 
    //counting to 100 million, using pre-increment. 
} 
$PreIncrementEnd=microtime(true); 
$i=0; 
$PostIncrementStart=microtime(true); 
for($i=0;$i<100000000;$i++){ 
    //counting to 100 million, using post-increment. 
} 
$PostIncrementEnd=microtime(true); 
$PreTime=$PreIncrementEnd-$PreIncrementStart; 
$PostTime=$PostIncrementEnd-$PostIncrementStart; 
if($PreTime<$PostTime){ 
    echo "the fastest was pre-increment. (which totally makes sense, it's consistent with c/c++, and it uses fewer opcodes than the post-increment, and the `old` value is not returned, only the new value, so we don't need 2 values (old value AND new value, as the post-increment does)..)"; 
} else { 
    echo "the fastest was post-increment... i am very surprised."; 
} 
echo "the difference was: ".abs($PreTime-$PostTime)." seconds.";