php tutorial - PHP Switch Statement - php programming - learn php - php code - php script



  • Switch statement is used to select one of the many blocks code to be executed.
  • You can use the “switch” statement to alter the flow of a program.
  • Conditional statements are used to perform actions on different conditions.
 Switch Statement

Learn PHP - PHP tutorial - Switch Statement - PHP examples - PHP programs

php scripts Syntax :

switch (n) {
    case label1:
        code to be executed if n=label1;
        break;
    case label2:
        code to be executed if n=label2;
        break;
    case label3:
        code to be executed if n=label3;
        break;
    ...
    default:
        code to be executed if n is different from all labels;
}
click below button to copy the code. php tutorial - team

Sample Code in php : sample php program

<!DOCTYPE html>
<html>
    <body>
        <?php
            $fruit = "mango";
            switch ($fruit) 
            {
                case "apple":
                    echo "My favorite fruit is apple";
                    break;
                case "mango":
                    echo "My favorite fruit is mango";
                    break;
                case "guava":
                    echo "My favorite fruit is guava";
                    break;
                default:
                    echo "Failure..!!!";
            }
        ?>
    </body>
</html>
click below button to copy the code. php tutorial - team

php programmer Code Explanation :

Code Explanation for Switch Statement In PHP

  1. In PHP, $fruit = "mango"; specifies the variable $fruit = mango variable holding the variable = mango.
  2. Here, switch ($fruit) will call the variable “$fruit” in the code, which we have specified as “mango”.
  3. We have the switch-cases as case “apple”, case “mango” and case “guava” which executes based on the function call for that variable ($fruit). If these cases fails it will execute the default case statement.
  4. break; is the statement that executes a line break in the code execution.

php development Sample Output :

output for Switch Statement In PHP

  1. Here the PHP statement executes the switch condition by printing the echo statement “My favorite fruit is mango”.


Related Searches to php switch statement