In this tutorial we will study about switch case control structure, switch case is used when we need to match a value with every cases, generally we include break statement after every switch case. Examples in this tutorial will make it more clear.
In this tutorial we will study about switch case control structure, switch case is used when we need to match a value with every cases, generally we include break statement after every switch case. Examples in this tutorial will make it more clear.Switch Case Control Structure:
Almost every modern language supports switch case control structure. It is similar to if statements. Switch case is useful when we need to compare a single variable with multiple possible values.
We should know how the switch case works, in switch case every case is considered or checked once and if the condition found true then PHP starts executing the statements until it found a break statement or the end of the switch case block. So, it is always better to put a break statement in case statement.
Example:
<?php
$a=10;
switch($a)
{
case($a%2==0):
echo"Even Number";
break;
case($a%2!==0):
echo "Odd Number";
break;
}
?>
Output:
Even Number
Example:
<?php
$a=12;
switch($a)
{
default:
echo "Default";
break;
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
}
?>
Output:
Default
Example:
<?php
$a=1;
switch($a)
{
case 1:
echo "One";
case 2:
echo "Two";
default:
echo "Default";
}
?>
Output:
OneTwoDefault