PHP switch
In this chapter you will learn:
- When to use switch statement
- Syntax for PHP switch statement
- Note for switch statement
- Example - Using PHP switch statement
Description
To test an expression against a range of different values, and does a different task depending on the matched value.
Syntax
In a switch/case block, you specify what you are checking against, then give a list of possible values you want to handle.
switch(value){/*from j a va 2 s . c om*/
case constant_1:
do if the value is constant_1
break;
case constant_2:
do if the value is constant_2
break;
case constant_3:
do if the value is constant_3
break;
default:
do if no one matched
break;
}
Note
Each case construct has a break
statement at the end of it.
break
exits the entire switch
construct,
ensuring that no more code blocks
within the switch
construct are run.
Example
The following code uses the switch statement to check string value.
<?php// java 2 s. c o m
$Name = 'Bob';
switch($Name) {
case "Jack":
print "Your name is Jack\n";
break;
case "Linda":
print "Your name is Linda\n";
break;
case "Bob":
print "Your name is Bob\n";
break;
default:
print "I don't know your name!\n";
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What is foreach loop
- foreach loop Syntax
- Example - Loop array with foreach loop
- Example - Iterating through a multidimensional array with foreach
- Example - Iterating Through Object Properties