Jump to content

switch statements


atholon

Recommended Posts

If you were to have a switch statement like this:

switch ($number)
{
case '1':
case '2':
$var = "hamburger";
break;
case '3';
$var = "french fry";
break;
default:
$var = "milk shake";
break;
}

How would the first case execute?

 

Would it be something like this?

if ($number= '1')
{
}
if ($number= '2')
{
$var = "hamburger";
}
else if ($number= '3')
{
$var = "french fry";
}
else 
{
$var = "milk shake";
}

Link to comment
https://forums.phpfreaks.com/topic/92092-switch-statements/
Share on other sites

Switch statements work similar to a waterfall. It will test each case going down until it finds a match, then will continue to run every subsequent case until it reaches a break. So, if $number equals 1, it would still set $var = "hamburger".

 

So think of it more like:

 

if ($number= '1' || $number = '2')
}
$var = "hamburger";
}
else if ($number= '3')
{
$var = "french fry";
}
else 
{
$var = "milk shake";
}

Link to comment
https://forums.phpfreaks.com/topic/92092-switch-statements/#findComment-471587
Share on other sites

But keep in mind, something like this:

 

<?php
$food = array();
switch ($number) {
  case '1':
    $food[] = "hamburger";
  case '2':
    $food[] = "potato chips";
    break;
  case '3';
    $food[] = "french fries";
    break;
  default:
    $var = "milk shake";
    break;
}
echo "I would like: ".implode(',',$food);
?>

 

will produce these results (note case 1):

CASERESULT

1I would like: hamburger,potato chips

2I would like: potato chips

3I would like: french fries

4I would like: milk shake

Link to comment
https://forums.phpfreaks.com/topic/92092-switch-statements/#findComment-471830
Share on other sites

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.