switch statement is a multi decision making statement. switch statement is used to execute one statement from multiple conditions.
Syntax:-
switch(expression){
case value1:
//statement to be executed
break;
case value2:
//statement to be executed
break;
......
default:
statement to be executed if all cases are not valid;
}
we have a single expression that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.
A switch statement is used to perform different actions, based on different conditions.
File name : index.php
<?php
$num= $_GET['number'];
switch($num){
case 1:
echo("number is equals to 7");
break;
case 2:
echo("number is equal to 8");
break;
case 3:
echo("number is equal to 6");
break;
default:
echo("number is not equal to 7, 8 or 6");
}
?>
File name : index.php
<?php
$user_role = 'admin';
$message = '';
switch ($user_role) {
case 'admin':
$message = 'Welcome, admin!';
break;
case 'editor':
$message = 'Welcome Editor';
break;
case 'author':
$message = 'Welcome Autor';
break;
case 'subscriber':
$message = 'Welcome Subscriber';
break;
default:
$message = 'You are not authorized to access this page';
}
echo $message;
?>
Example :-
File name : index.php
<?php
$country = $_GET['country_name'];
switch ($country) {
case "india":
echo "Your country is india.";
break;
case "pakistan":
echo "Your country is pakistan.";
break;
case "nepal":
echo "Your country is nepal.";
break;
default:
echo "Your default country is saudi.";
}
?>
Example :-
File name : index.php
<?php
$num = $_GET['num'];
switch ($num) {
case "1":
if($num > 5)
{
echo "number is greater than 5";
}
else
{
echo "number is lessthan than 5";
}
break;
case "2":
$number = 4;
$evod = $number % 2;
if($evod == 0)
{
echo "number is even no.";
}
else
{
echo "number is odd no.";
}
break;
default:
echo "Your default value is $num.";
}
?>
Example :-
File name : index.php
switch(true)
{
case (strlen($foo) > 30):
$error = "The value provided is too long.";
$valid = false;
break;
case (!preg_match('/^[A-Z0-9]+$/i', $foo)):
$error = "The value must be alphanumeric.";
$valid = false;
break;