PHP - SPLessons
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

[c]switch(expression) { case value1: //statements; break; case value2: //statements; break; case value3: //statements; break; case value n: //statements; break; default : //statements; break; }[/c] 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

[php] <!DOCTYPE html> <html> <body> <?php $x = 30; switch ($x) { case 40: echo "SP Lessons"; break; case 30: echo "Welcome to SPLessons"; break; case 60: echo "Welcome to SPLessons World!"; break; default: echo "SPLessons world welcomes you."; } ?> </body> </html> ?> [/php] Output:

Summary

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“.