Switchcase // suitable for matching a single value. this is a mutex. original PHP Tutorial: process control.
Multiple branches
If else if // suitable for range matching
Switch case // suitable for matching a single value. this is a mutually exclusive relationship.
------------------------------------------------------------------------
Syntax
If (condition ){
} Elseif (condition ){
} Elseif (condition ){
} Else if (condition ){
} Else {
}
Switch (variable ){
Case value:
Code;
Break;
Case value 1:
Code;
Break;
Default:
Code;
}
------------------------------------------------------------------------
Instance 1 // understand the mutex feature of multi-branch statements
$ Hour = date ("H ");
If ($ hour <6 ){
Echo "good morning ";
} Elseif ($ hour <9 ){
Echo "good morning ";
} Elseif ($ hour <12 ){
Echo "good morning ";
} Elseif ($ hour <14 ){
Echo "Good Noon ";
} Elseif ($ hour <17 ){
Echo "good afternoon ";
} Elseif ($ hour <19 ){
Echo "good evening ";
} Elseif ($ hour <22 ){
Echo "good evening ";
} Else {
Echo "good night ";
}
------------------------------------------------------------------------
Instance 2 // Determine the day of the week
$ Week = date ("D ");
Switch ($ week) {// swinch (variable) variables only use integer and string
Case "Mon ":
Echo "Monday ";
Break; // The break is used to exit the switch.
Case "Tue ":
Echo "Tuesday ";
Break;
Case "Wed ":
Echo "Wednesday ";
Break;
Case "Thu ":
Echo "Thursday ";
Break;
Case "Fri ":
Echo "Friday ";
Break;
Default: // if the variable does not have a matching value, execute the region in default. you can add
Echo "weekend ";
}
------------------------------------------------------------------------
Instance 3 // to better understand the break in the switch, it is used to set multiple values to match and execute the same code
$ Week = "Thursday ";
Switch ($ week ){
Case "Mon ":
Echo "Monday ";
Case "Tue ":
Echo "Tuesday ";
Case "Wed ":
Echo "Wednesday ";
Case "Thu ":
Echo "Thursday ";
Case "Fri ":
Echo "Friday ";
Default:
Echo "weekend ";
}
Final result: Thursday and Friday weekends
------------------------------------------------------------------------
Nested branch instance: // you can pass the http: // localhost/code1/10.php? parameter in this way? Sex = man & age = 15
$ Sex = $ _ GET ["sex"];
$ Age = $ _ GET ["age"];
If ($ sex = "nan "){
If ($ age> = 60 ){
Echo "this man has retired". ($ age-60). "years ";
} Else {
Echo "this man is still at work, and". (60-$ age). "He retired only in years.
";
}
} Else {
If ($ age> = 66 ){
Echo "this lady has retired". ($ age-55). "years ";
} Else {
Echo "this lady is still at work, and". (55-$ age). "she retired in years.
";
}
}