Shiphp The PHP Developer's Guide

Switch Statements in PHP

While the switch statement isn’t as popular as conditional operators like if and elseif in PHP, it can still be useful when evaluating a number of possible outcomes. Using a switch statement is pretty simple, so let’s look at an example:

<?php
$var = rand(0,2);
switch($var) {
    case 1:
        echo "The magic number is one.";
        break;
    default:
        echo "The magic number is unknown.";
}

This script will output either The magic number is unknown. or The magic number is one. depending on what random number is generated.

A More Advanced Example

You can extend the logic from our first example to more complex statements and cases.

<?php
$var = rand(0,5);
switch($var) {
    case 1:
        echo "The magic number is one.";
        break;
    case 2:
        echo "The magic number is two.";
        break;
    case $var > 2:
        echo "The magic number is too big!";
    default:
        echo "The magic number is unknown.";
}

This time, we’re evaluating a random number between 0 and 5 inclusive. The first two case statements work the same as above, but the third one is a little different. It evaluates whether the number is greater than 2 and if so it says the number is too big!. You may also notice that there’s no break; statement, meaning that if case $var > 2 is reached it will continue on to the default: statement as well. So your output might look like any one of the following:

As you can see, switch statements can be used to perform logical operations that would be cumbersome using only embedded if statements. They also tend to be more readable when you have lots of potential scenarios.

Like this Post?

Learn to build your first Dockerized PHP application.

In this book, PHP developers will learn everything they need to know to start building their applications on Docker, including:

  • Installing dependencies using Composer.
  • Getting data from a third-party API.
  • Saving data to a MySQL database.
  • Using a web framework (SlimPHP) for routing.
  • Storing environmental variables securely.
  • And much more!

You can buy this book on Leanpub today.

Buy it Now!