Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML
IMCreator - Free Website Builder

PHP Switch Statements

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

Code

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.

Code

The above code results in the following:

Sorry, don't know how much energy that vegetable contains.

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!