如何让php切换案例检查类型?

时间:2018-02-09 08:49:40

标签: php switch-statement identity equality

我希望切换案例与===而不是==进行核对。

<?php
$favcolor = "1";

switch ($favcolor) {
    case 1:
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "1":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green!";
}
?>

这给了我:

Your favorite color is red! 

但我希望它说绿色。怎么可能?

1 个答案:

答案 0 :(得分:1)

来自https://secure.php.net/manual/en/control-structures.switch.php

  

请注意,开关/外壳的比较松散。

使用开关无法实现此目的,请考虑使用if - elseif - else,例如:

if ( $favcolor === 1 )
    echo "Your favorite color is red!";
elseif ( $favcolor === "blue" )
    echo "Your favorite color is blue!";
elseif ( $favcolor === "1" )
    echo "Your favorite color is green!";
else
    echo "Your favorite color is neither red, blue, nor green!";