Switch Statements

In the C programming language, switch statement support arose out of the need for a little something extra when doing if/then types of computation. With the if/then statement, you are locked into a single condition. Switch statements allow for additional evaluations of the data, even though one of the cases may have been met. Switch statements can also save you from typing many if/elseif/elseif/… statements. PHP follows C's use of switch statements.

$a = "100"; 
switch($a) {
    case(10):
      echo "The value is 10";
      break;
    case (100):
      echo "The value is 100<br>";
    case (1000):
      echo "The value is 1000";
      break;
    default:
      echo "<p>Are you sure you entered a number?";
}

As you can see, switch statements have four basic parts:

  • The switch— ...

Get Advanced PHP for Web Professionals now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.