i

PHP Tutorial

Switch Statement

When you have multiple conditions to decide the code execution, then you can use switch statement. You get many blocks with a set of code to be executed based on the input given in the switch statement. The syntax for switch statement is below:

switch(expression input)

{

case label1:

code executed if expression input = label1;

break;

case label2:

code executed if expression input = label2;

break;

default:

code executed if none of the condition matches

For example, when you want to print the skill you are learning currently, you can create a variable as skill and add different blocks for various skills as below php code.

$skill = “php”; 

switch($skill)

{

case “java”

echo “ You are currently learning Java”;

break;

case “php”

echo “You are currently learning PHP”;

break;

default:

echo” You are neither learning Java nor PHP”;

}

?>

You can add multiple cases as you want as there is no limit to the cases and use break statement to prevent the next case to run if the match is found.