PHP Switch
The switch statement allows us to select among different options for value and run different pieces of code depending on which value it is set!
Syntax of switch:¶
switch(expression) { case value1: //operators1; break; case value2: //operators2; break; default: //default operators3; }
The switch statement is executed line by line. In the beginning, it checks the value of the expression, then controls the transferred case, which values is matched the value of the expression. If the value of the switch expression does not match anyone of the values cases, then goes to the operator, tagged as default.
<?php
$value = 2 ;
switch($value)
{
case 1:
echo ("case 1");
break;
case 2:
echo ("case 2");
break;
case 3:
echo ("case 3");
break;
default:
echo ("default");
}
// ouptput case 2
?>
When the value of the expression is matched cases, PHP continues to execute all codes, until it meets the operator break.
<?php
$value = 2 ;
switch($value)
{
case 1:
echo ("case 1");
case 2:
echo ("case 2");
case 3:
echo ("case 3");
}
// ouptput case 2 case 3
?>
A list of operators in the case also can be empty, he simply passes control to the next operator list of cases.
<?php
$value = 1 ;
switch($value)
{
case 1:
case 2:
echo ("value > 3 and value < 0 ");
break;
case 3:
echo ("case 3");
break;
default:
echo ("default");
}
// ouptput value > 3 and value < 0
Expression in the case statement can be any expression that evaluates to a simple type, that is the type integer, or a floating-point type (float), or a string. Arrays or objects can not be used here as long as they are not defined as a simple type.
0 Comments
CAN FEEDBACK
Emoji