Decision Making With Switch Statement in PHP

If you want execute one block of code out of many, use switch statement. The switch statement is to avoid long block of if..elseif..else code.
Below is switch statement syntax:-

switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}

Switch statement executes line by line and once finds a true condition it execute the corresponding block code and all other remaining cases till the end of switch statement.  To avoid this add a break statement at the end of each case block. The break statement tells the php to jump out of the switch case statement once it execute the code with first true case. If there is no matching case then the code in default block will be executed.

Difference between  if…else and switch case in PHP

The switch case statement is an alternative of if…elseif…else statement. The if…elseif…else statement also do same thing. The switch case statement finds a suitable block of code with true case and execute that code.

The only difference is that switch case statement is executed line by line and once a true condition is find not only executed that case but also execute all the subsequent cases till the end of switch statement. To prevent this break statement is used.

switch case in php
Switch Case Statement in PHP


Example:-

The following example will output current day.
 <?php
    $today = date("D");
    switch($today){
        case "Mon":
            echo "Today is Monday. ";
            break;
        case "Tue":
            echo "Today is Tuesday. ";
            break;
        case "Wed":
            echo "Today is Wednesday. ";
            break;
        case "Thu":
            echo "Today is Thursday.";
            break;
        case "Fri":
            echo "Today is Friday.";
            break;
        case "Sat":
            echo "Today is Saturday.";
            break;
        case "Sun":
            echo "Today is Sunday.";
            break;
        default:
            echo "This seems that some special day.";
            break;
    }
 ?>

Related Posts:

  • Decision Making With Switch Statement in PHP If you want execute one block of code out of many, use switch statement. The switch statement is to avoid long block of if..elseif..else code. Below is switch statement syntax:- switch (expression) { case label1: co… Read More

0 comments:

Post a Comment

Recent Post

All Loop Types in PHP

Loops are used to execute a block of codes until a certain condition is met. The main benefit of using a loop is to save the time and effor...

Popular Posts