How to use Switch Statement in PHP

In this article, I will explain how the Switch Statemen can be used in PHP.
  • 1951

Switch Statement in PHP

  • The switch statement is used to select one of many blocks of code to be executed.

  • The switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression)

{

case stage1:

  code to be executed if expression = stage1;

  break; 

case stage12:

  code to be executed if expression = stage2;

  break;

default:

  code to be executed

  if expression is different

  from both stage1 and stage2;

}

Example

The following example show how the Switch statement can be used in PHP.

<html>

<body>

<h3 style="color: darkorchid;">Switch statement example</h3>

    <?php

    $s=date_default_timezone_set('Asia/Kolkata');

    $d=date("D");

    ;

    switch ($d)

    {

    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 "Incorrect Data";

    }

    ?>

</body>

</html>

 

Output

switch.jpg

You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2019 DotNetHeaven. All rights reserved.