Lesson 8 – PHP Switch Statements

In this lesson, we study an extremely important component of PHP, the switch statements. They are very similar to If Statement. However, there are a couple of differences that you need to understand.

For example, if you want to test a variable against multiple conditions, you will have to write multiple if statements as shown in the following example.

<?php 
$snumber 

if ($number < 10) {
 echo "this";
}

if ($number < 10) {
 echo "this";
}

?>

It is a real hassle to write multiple if statements to check the same condition against multiple values. This is where switch statements come to your help. You can use one switch statement to check as many values as you want. Here is an example.

<?php 
$number = 90;

switch($number){

    case 34:
    echo "it is 34";
     break;
    case 37:
    echo "is it 34";
     break;
    case 90:
    echo "is it 90";
     break;
    case 24:
    echo "is it 24";
      break;
    
    default : 
     echo "we could not find anything";
    break;
}
?>

In the above example, “case” is the value against which Apache will test the condition “$number.” There are multiple cases in every switch statement. Apache will test each of these cases and as soon as the condition is fulfilled, it will print that case. The “break” in the code actually breaks the switch statement and informs Apache that it does not need to go any further. If none of the values fulfills the condition, the default “statement” will be published.

The output of the above code will be as under.

Switch statements are also super useful and that is why they are very popular among PHP programmers as well. They offer much more power and flexibility to programmers as compared to if statements. For instance, they allow them to test multiple conditions by writing fewer lines of codes.

In the next lesson, we will study PHP loops.