Latest Stories

In the previous lesson we used a PHP if... elseif statement in order to execute different block of code for each different condition. As mentioned, we could use as many "elseif"s as we like.
If you have many conditions, PHP switch statements are a more efficient way of doing this. The server will execute a PHP switch statement quicker than multiple "elseif"s. Also, there's actually less code for the programmer to write.
To write a PHP switch statement, you start with the switch keyword followed by the expression to evaluate (for example, a variable name). You then follow that with a case for each condition (based on the expression).

Syntax

switch (expression)
  {
  case value1
     code to be executed if the expression is equal to value1;
     break;
  case value2
     code to be executed if the expression is equal to value2;
     break;
  case value3
     code to be executed if the expression is equal to value3;
     break;
  default
     (optional) code to be executed if none of the above conditions are true.
     break;
  }

Example

In the following example, we declare a variable called $favoriteVege and assign a value to it. We then execute a switch statement in order to display a different string depending on the value of the variable.
Don't forget to end each case with a break;. This is required, otherwise all cases would be displayed.
$favoriteVege = "Fennel";
switch ($favoriteVege)
  {
  case "Gourd":
     echo "Your favorite vegetable has around 40 kilojoules of energy!";
     break;
  case "Artichoke":
     echo "One of those has around 105 kilojoules of energy!";
     break;
  case "Cassava":
     echo "One of those has around 550 kilojoules of energy";
     break;
  case "Potato":
     echo "That would be around 460 kilojoules of energy";
     break;
  default:
     echo "Sorry, don't know how much energy that vegetable contains.";
     break;
  }
The above code results in the following:
Sorry, don't know how much energy that vegetable contains.
Read More ...