PHP CASE 语句不适用于零值

PHP CASE statement not working with ZERO values(PHP CASE 语句不适用于零值)
本文介绍了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 时,返回high".这对我来说没有任何意义.有人可以解释这里发生了什么吗?

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) 即可.

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 语句不适用于零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)