php switch statement

PHP switch statement is a variant of the if-else combination, often used when you need to compare a variable against a large number of values.

Php Switch Statement Syntax

<?php
switch(variable being tested)
{
case value1:
statements to be executed
break;
case value2:
statements to be executed
break;
default:
statements to be executed
}
?>

The case keyword indicates possible matching values for the variable passed to switch(). When a match is made, every subsequent line of code is executed until the break keyword is encountered, at which point the switch statement comes to an end.

PHP Switch Statement Example


<?php
switch($myVar) {
case orange:
echo "This is orange";
break;
case 'apple':
echo "This is apple";
break;
default:
echo "orange And apple";
}
?>

The above example default message is "orange And apple" . otherwise if you assigen to value apple for "$myVar" variable the result will display "This is apple".

The main points to note about switch are as follows:

  • The expression following the case keyword must be a number or a string.
  • You can't use comparison operators with case. So case > 100: isn't allowed.
  • Each block of statements should normally end with break, unless you specifically want to continue executing code within the switch statement.
  • You can group several instances of the case keyword together to apply the same block of code to them.
  • If no match is made, any statements following the default keyword will be executed. If no default has been set, the switch statement will exit silently and continue with the next block of code.




Content