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