Php - Switch

About

This page is about the switch expression in php 1)

Example

Switch by value

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
       echo "i is not equal to 0, 1 or 2";
}

It is important not to forget break statements otherwise the switch statement runs all lines.

Fall out:

switch ($i) {
  case 0:
  case 1:
  case 2:
    echo "i is equal to 0 of 1 of 2";
    break;
  case 3:
    echo "i is 3";
}

Switch by expression

switch (true) {
    case $start - $offset === 1:
        print "A";
        break;
    case $start - $offset === 2:
        print "B";
        break;
    case $start - $offset === 3:
        print "C";
        break;
    case $start - $offset === 4:
        print "D";
        break;
}

Powered by ComboStrap