一次带有两个变量的 switch 语句 [英] switch statement with two variables at a time

查看:39
本文介绍了一次带有两个变量的 switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以建议使用以下 switch 语句的最佳方法吗?我不知道是否可以同时比较两个值,但这是理想的:

Could someone suggest the best way to have the following switch statement? I don't know that it's possible to compare two values at once, but this would be ideal:

switch($color,$size){
    case "blue","small":
        echo "blue and small";
    break;

    case "red","large";
        echo "red and large";
    break;
}


这可以与以下内容相媲美:


This could be comparable to:

if (($color == "blue") && ($size == "small")) {
    echo "blue and small";
}
elseif (($color == "red") && ($size == "large")) {
    echo "red and large";
}


更新我意识到我需要能够否定 ($color !== "blue") 并进行比较,而不是将变量等同于字符串.


Update I realized that I'll need to be able to negate ($color !== "blue") and compare as opposed to equating variables to strings.

推荐答案

你可以改变比较的顺序,但这仍然不理想.

You can change the order of the comparison, but this is still not ideal.

    switch(true)
    {
      case ($color == 'blue' and $size == 'small'):
        echo "blue and small";
        break;
      case ($color == 'red' and $size == 'large'):
        echo "red and large";
        break;
      default:
        echo 'nothing';
        break;
    }

这篇关于一次带有两个变量的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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