2014-01-17 43 views
1

我有一個簡單的PHP腳本來檢查數字的範圍。出於某種原因,一旦我檢查的號碼等於100%代碼不起作用。這裏是我的代碼:在PHP中檢查數字的範圍

$percent_completed = '100%';        

if ($percent_completed <= '20%') { 
    $color = 'danger'; 
} elseif ($percent_completed >= '21%' && $percent_completed < '40%') { 
    $color = 'warning'; 
} elseif ($percent_completed >= '40%' && $percent_completed < '60%') { 
    $color = 'info'; 
} elseif ($percent_completed >= '60%' && $percent_completed < '80%') { 
    $color = 'primary'; 
} elseif ($percent_completed >= '80%' && $percent_completed < '100%') { 
    $color = 'default'; 
} else { 
    $color = 'success'; 
} 

echo $color; 

所有上述工作就好了,直到$percent_completed條件檢查等於100%。出於某種原因,它設置爲100%$color打印出來的是danger。我相信這是一個簡單的修復,但我所嘗試過的一切都不起作用。

+2

你應該使用實數而不是字符串。而且,所有雙重條件的第一個條件是多餘的。 – jeroen

回答

8

從您的$percent_completed變量中刪除%變量。它使它成爲字符串,它會給你比作爲整數(對於數字)進行比較時有不同的結果。

$percent_completed = 100;        

if ($percent_completed <= 20) { 
    $color = 'danger'; 
} elseif ($percent_completed < 40) { 
    $color = 'warning'; 
} elseif ($percent_completed < 60) { 
    $color = 'info'; 
} elseif ($percent_completed < 80) { 
    $color = 'primary'; 
} elseif ($percent_completed < 100) { 
    $color = 'default'; 
} else { 
    $color = 'success'; 
} 

echo $color; 
+2

甚至不需要使用引號。這是一個整數 – Ryan

+1

@Ryan絕對正確。 –

+1

另外,不需要'> ='條件,因爲它們已經被滿足了。 – jeroen

4

你正在計算一個字符串。

這意味着「2%」實際上高於「100%」(例如)。

刪除百分比符號並在輸出期間需要時使用它。

1

你可以大大簡化這一點。

  • 刪除引號(數字爲整數)
  • 從您的百分比計算刪除%體徵
  • PHP正確處理了第一個成功if聲明和退出條件。從上到下堆疊,並使用1/2代碼。 (或者你可以把它寫下來,並用>代替)。

$p = 100;        
if ($p == 100) 
    $color = "success"; 
elseif ($p >= 80) 
    $color = "default"; 
elseif ($p >= 60) 
    $color = "primary"; 
elseif ($p >= 40) 
    $color = "info"; 
elseif ($p > 20) 
    $color = "warning"; 
elseif ($p <= 20) 
    $color = "danger"; 
echo $color; 
2

只是想指出的另一種方法,我張貼的替代解決方案。有時使用簡單的代數公式代替大量的if-else條件更具可讀性。

//Assign current percent value to a variable 
$percent_completed = 100; 
//Assign an array of all notifications 
$array_notifications = array("danger", "warning", "info", "primary", "default", "success"); 
//Calculate index of current notification 
$current_index = floor($percent_completed/20); 
//Print or do something else with detected notification type 
echo $array_notifications[$current_index]; 
+0

這是一個非常棒的解決方案 - 請注意,它依賴於'$ current_index'既是一個整數,也是'$ array_notifications'範圍內的結果。在這種情況下,它總是一個整數,所以沒關係。但是,要小心數組的基於0的索引 - 您需要執行一些操作,比如'$ array_notifications [$ current_index - 1]'。 – brandonscript

1

比較百分比串可以工作,如果您使用的是自然秩序比較功能。

自然順序比較函數將字符串和數字分開,並將數字視爲數字而不是字符串。

所以不是:

[ "1", "10", "2" ] 

您將獲得:

[ "1", "2", "10" ] 

有些語言有此功能,內置的(如PHP:strnatcmp),但可悲的是JavaScript的沒有。編寫你自己的實現並不是很難,但也不是很容易。

在這種情況下,我肯定會推薦簡化(如約翰的解決方案)。