PHP switch statement

Register here to save your progress

The switch statement runs a specific block of code from multiple ones based on a single expression (that usually is a variable). It works quite similar with multiple 'if' statements, stacked together, checking a single expression.

<?php

//set pressed button
$button_colour = 'red';
$flavour = '';

//pick the flavour
switch ($button_colour)
{
   case 'brown':
      $flavour = 'chocolate';
      break;
   case 'pink':
      $flavour = 'strawberry';
      break;
   case 'red':
      $flavour = 'cherry';
      break;
   case 'yellow':
      $flavour = 'mango';
      break;
   case 'black':
      $flavour = 'coffee';
      break;
   default:
      $flavour = 'vanilla';
}

//show picked flavour
echo 'You chose '.$flavour.' ice-cream.';

/*
will output 'You chose cherry ice-cream', since our button colour was red
this expression would be similar with the one bellow
*/

if($button_colour == 'brown')
{
      $flavour = 'chocolate';
}
elseif($button_colour == 'pink')
{
      $flavour = 'strawberry';
}
elseif($button_colour == 'red')
{
      $flavour = 'cherry';
}
elseif($button_colour == 'yellow')
{
      $flavour = 'mango';
}
elseif($button_colour == 'black')
{
      $flavour = 'coffee';
}
else
{
      $flavour = 'vanilla';
}

//show picked flavour
echo 'You chose '.$flavour.' ice-cream.';

As visible from the example above, when dealing with many similar repetitive expressions, switch can give a cleaner alternative to the if statement.