PHP Switch Statements

Switch statements can be used instead of If statements if you have many conditions to check for.

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

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.

The above code results in the following:

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