Jump to content

stacking switch cases


dennismonsewicz

Recommended Posts

Yes that is possible, eg

 

<?php

$animal = isset($_GET['animal']) ? $_GET['animal'] : '';

switch($animal)
{
   case 'dog':
   case 'cat':
   // etc
       echo 'You requested : ' $aniaml;
   break;

  default:
      echo 'Select an animal: <a href="test.php?animal=cat">Cat</a> | <a href="test.php?animal=dog">Dog</a>';
}

 

You can also do:

    case 'dog':
       // more code here
       // PHP will execute all code here, plus the code in the next case
   case 'cat':
   // etc
       echo 'You requested : ' $aniaml;
   break;

 

basically what is happening is PHP will execute all code within a switch/case until it comes across the break; keyword.

Link to comment
Share on other sites

To add to what wildteen said, it will execute the code if the condition evaluates true, for every condition.  It just won't skip the other condition checks if you leave out the break.  So in WT's examples, it won't execute the code if $animal != 'cat' 

 

You're sure about this?

 

Because this

 

<?php

$animal = 'dog';

switch($animal)
{
    case 'dog':

    case 'cat':
    // etc
        echo 'You requested : '. $animal;
    break;

   default:
       echo "none";
}
?>

 

echoes 'You requested : dog' here

Link to comment
Share on other sites

yes wildteen's example works!

 

<?php

$animal = $_GET['animal'];

switch($animal)
{
    case 'dog':
    case 'cat':
    // etc
        echo 'You requested : '. $animal;
    break;

   default:
       echo "none";
}
?>

 

I modified the $animal var to GET the animal from the URL, but it works like a charm! Thanks again!

Link to comment
Share on other sites

hmm...okay so it will not execute the script if the case evaluates false before the break, but it will after:

<?php

$animal = 'cat';

switch($animal)
{
   case 'dog': echo "dog";
   case 'cat': echo 'You requested : '. $animal;
   case 'pig' : echo "pig";
                  break;
  default:
      echo "none";
}
?>

 

That will output

 

You requested : catpig

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.