blerrr
blerrr

Reputation: 51

SWITCH-statement two case with same condition and also different condition

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

Upvotes: 2

Views: 2077

Answers (2)

CharlesEF
CharlesEF

Reputation: 628

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");

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80653

Since the variation of $pic between two cases is dependent on the value of $name, you can use $name itself:

switch($name) {
    case "Dog":
    case "Cat":
        $pic = "/images/" . strtolower($name) . ".jpg";
        $info ="four legs";
        break;
}

Upvotes: 2

Related Questions