PHP - SPLessons

PHP Switch

Chapter 15

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Switch

PHP Switch

shape Description

Switch case work like if statement, but here at a time N - Number of conditions can be checked in parallel. Each and every condition can be called as a block.If any conditions is matched in the Nth condition, then the controller will execute the respective block of statements.

Here in Switch statement, each and every conditional block will end with break. Using the break tag one can stop the controller from automatic executions of the next block.

Although most Switch statements can be rewrited with if statements, it tends to be easier for the compiler to optimize a large Switch statement than a long chain of if statements.

shape Syntax

case value1:

case value2:

case value3:

case value n:

default :

In the above syntax, “break” is the keyword used to end the case statements.

First, the expression is compared with case 1, if case 1 meets the criteria, then the corresponding statements gets executed until the break is reached. Otherwise (If it does not satisfy the condition then) switch goes to next case and the process continues. If neither case is satisfied then switch executes statements of “default case“.

shape Flow chart

shape Example

<!DOCTYPE html>
$x = 30;
switch ($x) {
case 40: echo "SP Lessons";
case 30: echo "Welcome to SPLessons";
case 60: echo "Welcome to SPLessons World!";
default: echo "SPLessons world welcomes you.";



shape Key Points

  • PHP Switch Statements checks ‘n’ number of conditions at a time.
  • Every conditional block will end with break.
  • If neither case is satisfied then switch executes statements of “default case“.