检查PHP中的数字范围

时间:2014-01-17 16:46:47

标签: php if-statement range

我有一个简单的PHP脚本,用于检查数字的范围。出于某种原因,一旦我检查的数字等于100%,代码就不起作用。这是我的代码:

$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%打印出的$colordanger。我确信这是一个简单的修复,但我尝试的一切都不起作用。

5 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

你正在对字符串进行计算。

这意味着'2%'实际上高于'100%'(例如)。

删除百分比符号,并在输出期间根据需要使用它。

答案 2 :(得分: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];

答案 3 :(得分: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;

答案 4 :(得分:1)

如果您使用自然顺序比较功能,则比较字符串可能

自然顺序比较函数将字符串和数字分开,并将数字视为数字而不是字符串。

所以而不是:

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

你会得到:

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

有些语言内置了这个功能(比如PHP:strnatcmp)但是JavaScript遗憾的是没有。编写自己的实现并不是很难,但也不是很容易。

在这种情况下,我肯定会建议简化(如John的解决方案)。