Introduction:
Switch / case is a type of decision making in php. Use Switch / case statement option when you have many options and have to execute one of those. This is helpful where you have to use long blocks of if..elseif..else code.
Syntax:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
switch (expression)
{
case label1:
if label expression is truecode here will be executed
break;
case label2:
if label expression is truecode here will be executed
break;
default:
code to be executed
if none of the above cases are true.
}
|
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<?php
$day_today=date("D");
switch ($$day_today)
{
case "Mon":
echo "Its Monday today";
break;
case "Tue":
echo "Its Tuesday today";
break;
case "Wed":
echo "Its Wednesday today ";
break;
case "Thu":
echo "Its Thursday today";
break;
case "Fri":
echo "Its Friday today";
break;
case "Sat":
echo "Its Saturday today";
break;
case "Sun":
echo "Its Sunday today";
break;
}
?>
|
Switch Statement – Default case
In the above example there is no chance that all of the none of the case will be true. However in many cases there will be situations where where all conditions/cases are false. In case of If statement we used else statement. In Switch statement we use Default case.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php
$State_Name = "NY";
switch ($State_Name){
case "NY":
echo "State Name is: New York <br />";
break;
case "AL":
echo "State Name is: Alabama <br />";
break;
case "IL":
echo "State Name is: Illinois <br />";
break;
default:
echo "Not in list, please add";
break;
}
?>
|
You can check by changing variable name value from NY to IL, Al and then to some other to check output.
Leave A Comment?