PHP switch Statement

      No Comments on PHP switch Statement

The PHP switch statement is used to perform different actions based on different conditions.

Syntax

switch (x) {
    case label1:
        code to be executed if x=label1;
        break;
    case label2:
        code to be executed if x=label2;
        break;
    case label3:
        code to be executed if x=label3;
        break;
    ...
    default:
        code to be executed if x is different from all labels;
} 

Let us see how it works

We have a variable or expression ‘x’. This expression ‘x’ is checked with value of each case. If there is a match, the block is executed.break is used to prevent code running to next case. When there is no match defaultblock is executed.

Example:

<?php
$day="Wednesday";
switch($day)
{
case "Monday":
echo "First day of the week";
break;
case "Tuesday":
echo "Second day of the week";
break;
case "Wednesday":
echo "Third day of the week";
break;
case "Thursday":
echo "Fourth day of the week";
break;
case "Friday":
echo "Fifth day of the week";
break;
case "Saturday":
echo "Sixth day of the week";
break;
case "Sunday":
echo "Seventh day of the week";
break;
default:
echo "Oops you do not match";
}
?>

Result:
Third day of the week

Leave a Reply

Your email address will not be published. Required fields are marked *