1.2.1177. Switch To Switch

The following structures are based on if / elseif / else. Since they have more than three conditions (not withstanding the final else), it is recommended to use the switch structure, so as to make this more readable.

On the other hand, switch() structures with less than 3 elements should be expressed as a if / else structure.

Note that if condition that uses strict typing (=== or !==) can’t be converted to switch() as the latter only performs == or != comparisons. Note that simple switch statement, which compare a variable to a literal are optimised in PHP 7.2 and more recent. This gives a nice performance boost, and keep code readable.

<?php

if ($a == 1) {

} elseif ($a == 2) {

} elseif ($a == 3) {

} elseif ($a == 4) {

} else {

}

// Better way to write long if/else lists
switch ($a) {
    case 1 :
        doSomething(1);
        break 1;

    case 2 :
        doSomething(2);
        break 1;

    case 3 :
        doSomething(3);
        break 1;

    case 4 :
        doSomething(4);
        break 1;

    default :
        doSomething();
        break 1;
}

?>

See also PHP 7.2’s switch optimisations and Is Your Code Readable By Humans? Cognitive Complexity Tells You.

1.2.1177.1. Suggestions

  • Use a switch statement, rather than a long string of if/else

  • Use a match() statement, rather than a long string of if/else (PHP 8.0 +)

1.2.1177.2. Specs

Short name

Structures/SwitchToSwitch

Rulesets

All, Analyze

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

switch, match

Examples

Thelia, XOOPS

Available in

Entreprise Edition, Exakat Cloud