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.

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' 

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

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!

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.