PHP:与零比较

时间:2014-09-06 18:24:27

标签: php comparison

<?php
$value = 0;
switch ($value) {
    case $value < 3:
        $output = 'smaller than 3';
        break;
    case $value >= 3 && $value <= 4:
        $output = 'between 3 and 4 (inclusively)';
        break;
    case $value >= 5 && $value <= 6:
        $output = 'between 5 and 6 (inclusively)';
        break;
    case $value >= 6 && $value <= 7:
        $output = 'between 6 and 7 (inclusively)';
        break;
}
echo $output;
?>

为什么输出between 3 and 4 (inclusively)而不是smaller than 3

............................................... ...................................

1 个答案:

答案 0 :(得分:0)

switch()应为true,但$value0。零被视为false。对于条件,您只需使用if然后elseif。试试这个..

$value = 0;
if($value < 3){
    $output = 'smaller than 3';
}elseif($value >= 3 && $value <= 4){
    $output = 'between 3 and 4 (inclusively)';
}elseif($value >= 5 && $value <= 6){
    $output = 'between 5 and 6 (inclusively)';
}elseif($value >= 6 && $value <= 7){
    $output = 'between 6 and 7 (inclusively)';
}
echo $output;

<强>输出: smaller than 3