$bytes = 0;
switch($bytes){
case $bytes == 0:
echo 'Equal to 0.';
break;
case $bytes < 0:
echo 'Less than 0.';
break;
}
這會輸出「小於0」。PHP開關功能不識別「小於0」
爲什麼?
$bytes = 0;
switch($bytes){
case $bytes == 0:
echo 'Equal to 0.';
break;
case $bytes < 0:
echo 'Less than 0.';
break;
}
這會輸出「小於0」。PHP開關功能不識別「小於0」
爲什麼?
switch
聲明不起作用。當檢查每個case
時,將該值與case
值(使用==
)進行比較。
所以,PHP是這樣做的:
$bytes == ($bytes == 0)
?這是:$bytes == (true)
。這是false
,所以它被跳過。$bytes == ($bytes < 0)
?這是:$bytes == (false)
。這是true
,所以它運行該塊。您需要在這裏使用if/else
。
$bytes = 0;
if($bytes == 0){
echo 'Equal to 0.';
}
elseif($bytes < 0){
echo 'Less than 0.';
}
我想case是相當於IF表達式==真,猜我錯了 – nick 2012-07-26 21:54:42
'case'相當於如果'$ value ==表達式'。 – 2012-07-26 21:56:14
詳細說明: case語句評估給定的值並將所選變量與它進行比較。在這種情況下,'$ bytes == 0'爲真('1'的值),這不等於'$ bytes'。然後它嘗試'$ bytes <0',這是false(值爲'0'),因此執行該塊。 – 2012-07-26 21:56:54
您不能在switch語句中使用運算符。它實際上應該是:
$bytes = 0;
switch($bytes){
case 0:
echo 'Equal to 0.';
break;
default:
echo 'Something else';
break;
}
看一看完整的文檔:http://www.php.net/manual/en/control-structures.switch.php
爲什麼你的樣品結果「小於零」?簡單的問題: ($字節< 0)評估爲假,因爲它不是。 False等於0,所以它匹配$字節並落入該情況。
如果您需要匹配某些範圍,您必須使用if-else-constructs。
一個老問題,但還有另一種使用開關的方法:)我在SitePoint上找到它!
switch (true) {
case $bytes == 0: // result of this expression must be boolean
echo 'Equal to 0.';
break;
case $bytes < 0: // result also must be boolean
echo 'Less than 0.';
break;
default:
}
說明:如果true == ($bytes == 0)
或者true == ($bytes > 0)
或default:
可以使用switch (false) {}
如果你有很多falsy結果,而不是x != y
那是不是交換機的工作原理.. – 2012-07-26 21:53:11
它讀取$字節== 0作爲「真」和$字節<0作爲「假」..由於$字節是0,它匹配0與假。我需要休息一下...... – nick 2012-07-26 21:59:47
是的,這是一個很好的答案..考慮在下面添加它(因爲它*解釋*的行爲):) – 2012-07-26 22:01:18