Switch
The switch statement in PHP allows you to execute a block of code based on a specific value or expression.
Here is an example of a switch statement in PHP:
$x = 10;
switch ($x) {
case 10:
echo "x is equal to 10";
break;
case 11:
echo "x is equal to 11";
break;
default:
echo "x is not equal to 10 or 11";
break;
}
In this example, the code inside the first case block will be executed because the value of $x is equal to 10. The break statement at the end of each case block causes the switch statement to exit and stop executing any further code. If the break statement is omitted, the switch statement will continue to execute the code in the next case block, even if the condition has not been met.
The default case is optional, and it specifies a block of code to be executed if none of the other case conditions are met.
You can also use the switch statement to compare the type of a variable, rather than its value:
$x = 10;
switch (gettype($x)) {
case "integer":
echo "x is an integer";
break;
case "string":
echo "x is a string";
break;
default:
echo "x is not an integer or a string";
break;
}
In this example, the code inside the first case block will be executed because the type of $x is an integer.