dstt1818 2015-11-14 00:26
浏览 296
已采纳

SWITCH语句两种情况相同且条件不同的情况

Hi I wonder if this could be done in switch case. Here's the example code I wanna do

switch($name)
case "Dog":
    $pic = "/images/itscute.jpg";
    $info ="four legs";
    break;
case "Cat":
    $pic = "/images/cat.jpg";
    $info ="four legs";
    break;
case "bird":
    $pic = "/images/bird.jpg";
    $info = "two legs";
    break;

Now you can see that both of dog and cat have the same value of $info. Does it possible for me to make $info only one for both of them like this

switch($name)
case "Dog":
case "Cat":
    $info ="four legs";
    break;
case "bird":
    $info = "two legs";
    break;

then again I don't know how to place the $pic if the code like this.

EDIT : $pic at dog is not "/images/dog.jpg";

EDIT2 : added more case to be more clear question

  • 写回答

2条回答 默认 最新

  • douliao8318 2015-11-14 02:35
    关注

    For any variables that contain the same value why use a switch at all? Just define those variables before the switch statement. Use the switch statement only for variables that contains different values.

    EDIT

    In that case there is no reason why you can't use 2 switch statements, like this:

    switch(strtolower($name))
    {
    case "dog":
        $pic = "/images/itscute.jpg";
        break;
    case "cat":
        $pic = "/images/cat.jpg";
        break;
    case "bird":
        $pic = "/images/bird.jpg";
        break;
    }
    switch(strtolower($name))
    {
    case "dog":
    case "cat":
        $info = "four legs";
        break;
    case "bird":
        $info = "two legs";
        break;
    }
    

    I do recommend that you use strtolower(), like my example shows, to avoid any case problems. You can use any number of switch statements as you need. As for turning "dog" into "Dog's" just add the "'s" to the variable, like this: $name = ucwords($name . "'s");

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加