php

PHP Switch Statement

The ‘switch‘ statement is used in PHP to implement conditional statements like the ‘if-elseif-else‘ statement. The purpose of the ‘switch’ statement is to execute the particular statement(s) based on the matching condition from the multiple conditions. But some comparisons that can be implemented by the ‘if-elseif-else‘ can’t be implemented by the ‘switch‘ statement. The uses of the ‘switch’ statement in PHP have shown in this tutorial.

Syntax:

switch(n){

    case label1:

        // Code to be executed if n=label1

        break;

    case label2:

        // Code to be executed if n=label2

        break;

    ...

    default:

        // Code to be executed if n is different from all labels

}

The value of the n will be checked with each case label value and the statement(s) of the case block will be executed where the value of the case label matches with n. The break statement is used to terminate from the switch block if the match is found.

Pre-requisite

The scripts used in the examples of this tutorial are written based on the PHP 8 version. Do the following task before executing the examples of this script.

  1. Install apache2 and PHP 8.
  2. Set execute permission for all files and folders under /var/www/html folder where all PHP files will be stored.

Different Uses of Switch Statement

Different uses of the switch statement in PHP have been shown in this part of this tutorial by using multiple examples.

Example-1: Simple use of switch..case statement

Create a PHP file with the following script to check the simple use of the ‘switch’ statement. Here, the $found variable is used to check the variable $book_name matches with any case value or not.

<?php


//Initialize the book name for checking

$book_name = 'PHP & MySQL Novice to Ninja';

$found = True;

//Start of switch block

switch ($book_name) {

    //Check the first case value

    case "Head First PHP & MySQL" :

        $author = "Lynn Beighley & Michael Morrison";

        $publisher = "O'Reilly";

        break;

    //Check the second case value

    case "PHP & MySQL Novice to Ninja":

        $author = "Tom Butler & Kevin Yank";

        $publisher = "SitePoint";

        break;

    //Check the third case value

    case "PHP: A Beginner’s Guide":

        $author = "Vikram Vaswani";

        $publisher = "McGraw-Hill Education";

        break;

    //Set the $found to false

    default:

        $found = False;

}


if($found == True)

    echo "<b>Book:</b>$book_name<br/><b>Author:</b>$author<br/><b>Publisher:</b>$publisher<br/>";

else

    echo 'The book information not found.';

Output:

The following output will appear after executing the above script. Here, the filename is switch1.php that is stored inside /var/www/html/code folder.

http://localhost/code/switch1.php

Example-2: Use of multiple case statements together

Create a PHP file with the following script to check the way of using the ‘switch’ statement by combining multiple case statements. Here, the value of $ID will be assigned by reading the URL query parameter named ‘id’. The value of $ID will be checked by the switch..case statement later to generate the output.

//Check the ID value has passed in the URL or not
if(isset($_GET['id']))

    $ID = $_GET['id'];

else

    $ID='';


//Define the swith block

switch ($ID) {

    //Set same information for three ID values

    case '07967':

    case '07895':

    case '07342':

        $text = ' is the ID of a CSE student.';

        break;

    //Set information for a particular ID value

    case '04523':

        $text = ' is the ID of a English student.';;

        break;

    //Set same information for two ID values

    case '01876':

    case '01907':

        $text = ' is the ID of a BBA student.';

        break;

    //Set message for empty ID value

    default:

        $text = '<center><h3>No Matching information found.</h3></center>';

}


echo "<center><h3>$ID$text</h3></center>";

Output:

The following output will appear after executing the above script without any query parameter. Here, the filename is switch2.php that is stored inside /var/www/html/code folder.

http://localhost/code/switch2.php

The following output will appear after executing the above script with the query parameter named “id” and the value is “07895” that matches with the first case block.

http://localhost/code/switch2.php?id=07895

The following output will appear after executing the above script with the query parameter named “id” and the value is “01907” that matches with the third case block.

http://localhost/code/switch2.php?id=01907

Example-3: Use of Logical ‘OR’ operator in switch..case statement

Create a PHP file with the following script to check the way of using ‘switch’ statement in which the ‘case’ statement is defined by Logical OR operator. Here, the value the of $name will be assigned by reading the URL query parameter named ‘name’. The value of $name will be checked by the ‘switch..case’ statement later to generate the output.

<?php

//Check the name value has passed in the URL or not

if(isset($_GET['name']))

    $name = strtoupper($_GET['name']);

else

    $name='';


//Define the swith block with True

switch(True)

{
        case ($name == "ABIR"):

        echo "<center><h3>$name is the team leader.</h3></center>";

        break;

       //Match any of the three values using logical OR

        case ($name == "RIYA" || $name == "RESMA" || $name == 'MAHBUB'):

        echo "<center><h3>$name is a team member.</h3></center>";

        break;

    case ($name == "KARIM"):

        echo "<center><h3>$name is the organizer.</h3></center>";

        break;

    default:

        echo "<center><h3>No information found.</h3></center>";

}

?>

Output:

The following output will appear after executing the above script with the query parameter named “name” and the value, “riya”. Here, the filename is switch3.php that is stored inside /var/www/html/code folder.

http://localhost/code/switch3.php?name=riya

The following output will appear after executing the above script with the query parameter named “name” and the value, “karim”.

http://localhost/code/switch3.php?name=karim

Example-4: Use of the array in switch..case statement

Create a PHP file with the following script to check the way of using the ‘switch’ statement in which the ‘case‘ statement is defined the particular array. Here, three arrays have been declared in the script with three types of values. the value of $var will be assigned by reading the URL query parameter named ‘var’. The value of $var will be checked by the ‘switch..case’ statement later by using the loop to generate the output.

<?php

//Declare three types of array

$array1 = [10, 23, 56, 32, 90, 11];

$array2 = [7.9, 3.6, 7.8, 2.9, 6.3, 1.2];

$array3 = ['book', 'pen', 'pencil', 'scale'];


//Check the value of the var has passed in the URL or not

if(isset($_GET['var']))

    $val = $_GET['var'];

else

    $val ='';


//Define the switch block

switch (true) {

    //Check in the first array

    case in_array($val, $array1) :

        echo "<br/><center><p><b>$val</b>exists in the first array.</p></center>";

        break;

    //Check in the second array

    case in_array($val, $array2) :

        echo "<br/><center><p><b>$val</b>exists in the second array.</p></center>";

        break;

    //Check in the third array

    case in_array($val, $array3) :

        echo "<br/><center><p><b>$val</b>exists in the third array.</p></center>";

        break;

    default:

        echo "<br/><center><p>The value does not exist in any array.</p></center>";

}

Output:

The following output will appear after executing the above script with the query parameter named “var” and the value, “32”. Here, the filename is switch4.php that is stored inside /var/www/html/code folder.

http://localhost/code/switch4.php?var=32

The following output will appear after executing the above script with the query parameter named “var” and the value, “2.9”.

http://localhost/code/switch4.php?var=2.9

The following output will appear after executing the above script with the query parameter named “var” and the value, “pencil”.

http://localhost/code/switch4.php?var=pencil

Conclusion

The switch..case statement is a useful conditional statement for many programming tasks. The way to check the value of the simple variable, use the logical operator with the variable and use of array with the variable in the switch..case statement has described in this tutorial.

Video Tutorial

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.