PHP CASE语句不适用于零值 [英] PHP CASE statement not working with ZERO values

查看:48
本文介绍了PHP CASE语句不适用于零值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这里发生了什么.从逻辑上来说,这对我来说没有任何意义.

I don't understand what's happening here. Logically, it doesn't make any sense to me.

<?php
$level = 0;

switch ($level) {

  case $level > 80: $answer = 'high'; break;
  case $level > 60: $answer = 'moderate-to-high'; break;
  case $level > 40: $answer = 'moderate'; break;
  case $level > 20: $answer = 'low-to-moderate'; break;
  default: $answer = 'low'; break;
}   
echo $answer;
?>

当$ level == 0时,它返回高".这对我来说没有任何意义.有人可以解释这里发生了什么吗?

When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?

推荐答案

switch ($level)更改为switch (true),这将起作用.

Change switch ($level) to switch (true) and this will work.

switch 语句对案件. PHP正在评估您的>比较,因此case $level > 80变为case false. false被认为等于0,因此第一种情况匹配.

switch statements perform equality tests on the values in the cases. PHP is evaluating your > comparisons, so case $level > 80 becomes case false. false is considered to be equal to 0, so the first case matches.

这篇关于PHP CASE语句不适用于零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆