|
‘Switch’ statement is conditional statement used to perform different action
based on different condition. I.e. switch statement is used to select one of
many blocks of code to be executed.
The switch statement is a control statement that handles multiple selections by
passing control to one of the case statements within its body.
The switch statement is similar to a series of IF statements on the same
expression. In many occasions, you may want to compare the same variable (or
expression) with many different values, and execute a different piece of code
depending on which value it equals to. This is exactly what the switch statement
is for.
Syntax:
switch (expression)
{
case label_1:
code to be executed
if expression = label_1 ;
break;
case label_2:
code to be executed
if expression = label_2;
break;
.............
.............
default:
code to be executed
if expression is not equal to all
label_1, label_2,... etc.
}
Let’s we have an example, how to implement switch statement in PHP.
Example:
<html>
<head>
<title> Switch Statement</title>
</head>
<body>
<?php
//
Declare
a
variable
which
is
stores
product
name
$product_Name
=
"Mouse";
switch ( $product_Name )
{
case
"Monitor" :
echo
"This is monitor
section";
break;
case
"Keyboard" :
echo
"This is Keyboard
section";
break;
case
"CPU" :
echo
"This is CPU
section";
break;
case
"Mouse" :
echo
"This is mouse
section";
break;
default:
echo
"All above block
of code not executed this is default section";
}
?>
</body>
</html>
Desired Output:
|