Page 61 - Open Soource Technologies 304.indd
P. 61
Unit 3: Flow-Control Statements and PHP in Web Page
If an expression successfully evaluates to the values specified in more than one case statement, Notes
only the first one encountered will be executed. Once a match is made, PHP stops looking for
more matches.
In the following case, the second case will never be executed, because anything greater than 1000
is also greater than 100.
switch ($someNumber) {
case $someNumber > 100:
echo “The number is greater than 100.”;
break;
case $someNumber > 1000:
echo “The number is greater than 1000.”;
break;
}
The way around this is just to make sure that the conditions are specified in the correct order for
what you want them to do.
switch ($someNumber) {
case $someNumber > 1000:
echo “The number is greater than 1000.”;
break;
case $someNumber > 100:
echo “The number is greater than 100.”;
break;
}
Default Condition
The default keyword is a catch-all case that marks the point to begin execution of none of the
conditions being tested for is met. It is like the last else statement in a long string of elseif’s.
Like the last else, it should always appear at the end of the switch statement, since it will always
be executed if no previous match has been made, and since PHP stops looking when it finds a
match. default is always a match if it is reached. You should only use it if you have code that is
to be run if none of the conditions are met. For instance, error code to report that the expression
did not evaluate to an expected value.
Break Statement
The break keyword is a statement that says that we are done performing statements within this
statement block and that we should exit immediately to the end of the statement block. If you
forget the break statement, then the code will fall through, which is to say that the code will start
executing at the label that matches the value of the expression being evaluated, and then will
proceed to process all codes until either the end of the switch statement or until it finds a break
statement, whichever comes first. If done intentionally, this can be useful. If done by mistake it
can be a real problem.
Here is a good use of omitting break statements. It allows us to perform the same black of code
for multiple possible values of the expression being evaluated.
LOVELY PROFESSIONAL UNIVERSITY 55