Logo
/
Programming
/
PHP Course
/

Switch construction

PHP: Switch construction

In many languages, besides the conditional if construct, there's also a switch. This construct appears in a huge amount of existing PHP code, so it's important to be able to read it.

It's a specialized version of if, created for certain special situations. For example, it makes sense to use it where there's an if else chain with equality checks. For example:

<?php

if ($status === 'processing') {
    // Doing it once
} elseif ($status === 'paid') {
    // Doing it twice
} elseif ($status === 'new') {
    // Doing it three times
} else {
    // Doing it four times
}

This composite check has one distinguishing feature, each branch here is a check for the value of the status variable. Switch allows you to write this code in a shorter and more expressive way:

<?php

switch ($status) {
    case 'processing': // status == processing
        // Doing it once
        break;
    case 'paid': // status == paid
        // Doing it twice
        break;
    case 'new': // status == new
        // Doing it three times
        break;
    default: // else
        // Doing it four times
}

A switch is a rather complicated construction in terms of the number of elements it consists of:

  • An external definition containing the keyword switch. A variable whose values switch use to select a behavior. And curly brackets for behavior branches.
  • The case and default constructions, where the behavior for different values of the variable is described. Each case corresponds to an if in the example above. default is a special situation, corresponding to the else branch in conditional constructions. Like with else, there's no need to specify default.
  • break is needed to prevent it from not working properly. If it's not specified, then after the desired case is executed, the execution will go to the next case and so on either until it reaches the nearest break, or until the end of the switch.

The curly brackets in the switch don't define a block of code like they did elsewhere. Only the syntax shown above is acceptable. In other words, you can use case or default there. But inside each case (and default) the situation is different. You can execute any code you like here:

<?php

switch ($count) {
    case 1:
        // Doing something useful
        break;
    case 2:
        // Doing something useful
        break;
    default:
        // Doing something
}

Sometimes, the result inside case means ending the function containing the switch. If this happens, you need to return it outside somehow. There are two ways to do this.

The first way. Create a variable before switch, fill it with something in case and then return the value of that variable outward at the end.

<?php

function doSomethingGood(int $count): ?string
{
    // Filling it
    switch ($count) {
        case 1:
            $result = 'one';
            break;
        case 2:
            $result = 'two';
            break;
        default:
            $result = null;
    }

    // Return
    return $result;
}

The second way is easier and shorter. Instead of creating a variable, case allows you to internally do a normal return from a function. And since no code is executed after return we can get rid of break:

<?php

function doSomethingGood(int $count): ?string
{
    switch ($count) {
        case 1:
            return 'one';
        case 2:
            return 'two';
        default:
            return null;
    }
}

Though switch is present in the code, you can always find a way to avoid it. The key benefit of using it is that it better expresses the programmer's intention when checking the values of a particular variable. Although there's now physically more code, it's easier to read than loads of elseif blocks.

Instructions

Implement the getNumberExplanation() function, which takes a number as input and returns an explanation of that number. If there's no explanation for the number, then just a number is returned. Explanations exist only for the following numbers:

  • 666 - devil number
  • 42 - answer for everything
  • 7 - prime number

Function call examples:

<?php

getNumberExplanation(8); // just a number
getNumberExplanation(666); // devil number
getNumberExplanation(42);  // answer for everything
getNumberExplanation(7);   // prime number

Tips

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!