PHP - Statement switch Statement

Introduction

With the switch statement, you include the expression to test only once.

Then provide a range of values to test it against, with corresponding code blocks to run if the values match.

<?php
        $userAction = "";
        switch ( $userAction ) {
          case "open":
            // Open the file
            break;
          case "save":
            // Save the file
            break;
          case "close":
            // Close the file
            break;
          case "logout":
            // Log the user out
            break;
          default:
            print "Please choose an option";
         }
?>

The switch statement includes the condition to test: the value of the $userAction variable.

A series of case statements test the expression against various values: "open" , " save" , and so on.

If a value matches the expression, the code following the case line is executed.

If no values match, the default statement is reached, and the line of code following it is executed.

Each case construct has a break statement at the end of it.

When PHP finds a case value that matches the expression, it not only executes the code block for that case statement, but it then also continues through each of the case statements that follow, as well as the final default statement, executing all of their code blocks in turn.

The break exits the entire switch statement, ensuring that no more code blocks within switch construct are run.

Fall through

For example, the following script asks the users to confirm their action only when they're closing a file or logging out:

Demo

<?php

         switch ( $userAction ) {
           case "open":
             // Open the file
             break;
           case "save":
             // Save the file
             break;
           case "close":
           case "logout":
             print "Are you sure?";
             break;
           default:
             print "Please choose an option";
          }/*  w  w w.ja  v  a2 s  .c o  m*/
?>

Result

If $userAction equals "open" or "save" , the script behaves like the previous example.

However, if $userAction equals "close" or "logout", it runs the same code.

Related Topic