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条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?