PHP Switch Statement Tutorial

This video tutorial covers PHP flow control, in particular switch statements.

What Are Conditional Statements

In PHP, conditional statements are used to have PHP scripts execute a set of pre-determined actions if a given condition (or conditions) is true and another set of pre-determined actions if a given condition (or conditions) is false. There are two conditional structures in PHP: if, elseif and else statements and switch statements.

The list below gives you a brief description of each conditional statement.

  • if statement - this conditional statement executes a set of instructions only if a specified condition is true
  • if...else statement - this conditional statement executes a set of code if a condition (or conditions) is true and another set of instructions if the condition is false
  • if elseif else statement - this conditional statement executes one of several sets of instructions depending on whether one (or more) set of conditions is true or false
  • switch statement - this conditional statement is similar to a series of if elseif and else statements. Switch statements should be used when there are more than a few set of conditions which can be true or false

switch Statements

switch statements are similar to a series of if elseif and else statements. Switch statements should be used when there are more than a few set of conditions which can be true or false.

The syntax of a switch statement is shown below.

switch (case) { case value #1: code to be executed if case = value #1; break; case value #2: code to be executed if case = value #2; break; default: code to be executed if n is different from both value #1 and value #2; }

First we have a single expression (case) which is most often a variable that is evaluated once. The value of the expression is then compared with the value of each case in the switch statement. If there is a match, the block of code that is associated with that case is executed. The keyword 'break', is used to prevent the next block of code from executing. The code in the default statement is executed if there is not match found.

The PHP code below is an example of a switch statement.

$name = 'Billy'; switch ($name) { case 'Adam': echo 'Hi Adam'; break; case 'Billy': echo 'Hi Billy'; break; default: echo 'Hi there'; }

The PHP code above would output the text 'Hi Billy', because the case is equal to Billy. If the case were equal to 'Adam', the output would be 'Hi Adam'. If the case did not match either 'Adam' or 'Billy', the output would be 'Hi there'.