PHP switch语句匹配错误:输入2023时触发首个case问题排查
PHP Switch语句匹配错误原因分析
问题场景
输入出生年份2023时,计算得到年龄为0,预期匹配第二个case输出对应内容,但实际触发了第一个case。
原代码
$year = readline('Type your year of birth: '); $age = 2023 - $year; switch ($age) { case ($age < 0): echo "I don't see in the future."; break; case ($age >= 0) && ($age <= 3): echo 'Congrats. A newborn capable of using the PC.'; break; case ($age > 3): echo 'Our system calculated that you are:' . ' ' . $age . ' ' . 'years old'; break; }
错误原因
PHP的switch语句逻辑是:将switch()括号内的变量值,与每个case后的值做松散相等(==)比较,而非直接判断case中的表达式是否成立。
当输入2023时,$age = 0:
- 第一个
case ($age < 0)会先计算表达式,得到布尔值false;随后PHP拿$age的0和false做松散比较,在PHP中0 == false结果为true,因此直接匹配第一个case执行。 - 第二个
case ($age >=0 && $age <=3)计算后得到布尔值true,而0 == true结果为false,所以不会匹配该case。
修正方案
方案1:使用if-else(推荐,逻辑更清晰)
$year = readline('Type your year of birth: '); $age = 2023 - $year; if ($age < 0) { echo "I don't see in the future."; } elseif ($age >= 0 && $age <= 3) { echo 'Congrats. A newborn capable of using the PC.'; } else { echo "Our system calculated that you are: $age years old"; }
方案2:调整switch的判断逻辑
如果一定要用switch,可以将switch的判断值设为true,让每个case的表达式结果与true比较:
$year = readline('Type your year of birth: '); $age = 2023 - $year; switch (true) { case $age < 0: echo "I don't see in the future."; break; case $age >= 0 && $age <= 3: echo 'Congrats. A newborn capable of using the PC.'; break; default: echo "Our system calculated that you are: $age years old"; }
内容的提问来源于stack exchange,提问作者user21100580
相关产品推荐
相关产品推荐

