PHP - Switch...case

Introduction

switch...case structure evaluates only one expression, and executes the block depending on its value.

Demo

<?php 
    $title = "Java";
    switch ($title) { 
        case 'Java': 
            echo "Nice story."; 
            break; 
        case 'Lord of the Rings': 
            echo "A classic!"; 
            break; 
        default: 
            echo "else."; 
            break; 
     } //from  ww  w. j  ava  2  s.  co m
?>

Result

The switch clause takes an expression, in this case a variable, and then defines a series of cases.

When the case matches the current value of the expression, PHP executes the code inside it.

As soon as PHP finds a break statement, it exits the switch...case.

In case none of the cases are suitable for the expression, PHP executes the default, if there is one, but that is optional.

Related Topics