如何让php开关大小写检查类型?

How to make php switch case check for type?

提问人:tgwtdt 提问时间:2/9/2018 更新时间:2/9/2018 访问量:495

问:

我希望用开关盒而不是 .=====

<?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! 

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

PHP switch-语句 标识 相等

评论

3赞 brombeer 2/9/2018
手册中:“请注意,开关/外壳确实比较松散。"

答:

1赞 myxobek 2/9/2018 #1

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

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

你不能使用 switch 来实现这一点,请考虑使用 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!";