Switch

The next example looks at the value for month and prints the season if it is a valid month.

We can use && to test for a valid month: if($month>=1 && $month<=12)

Or we can use || to test for an invalid month: if($mont<1 || $month>12)

If it is a valid month we can print the season using

if($month==3 || $month==4 || $month==5) echo 'Spring';

However, there is an easier way, switch. The switch construct offers an alternative to nested if statements. Switch can be used when a variable has a small number of possible values.

In a switch statement the variable to test is in parenthesis after the word switch: switch($month) {
The value of the variable is compared to each case. When a match is found, statements are executed until a break is encountered. If no case matches, the statements after the word default are executed.
The switch block requires braces at the beginning and end. A common source of errors is forgetting to put in a break; Try the example and remove one of the breaks to see what happens.

Example: Printing the season based on month using switch.
<?php
switch($month) {
  case 12: case 1: case 2: echo 'winter'; break;
  case 3: case 4: case 5: echo 'spring'; break;
  case 6: case 7: case 8: echo 'summer'; break;
  case 9: case 10: case 11: echo 'fall'; break;
  default: echo $month.' is not a valid month';
}
echo '<BR>';
?> 
TEST PAGE
INDEX, Boolean Values, if/else, Summary, Compound Conditions: AND && and OR ||, SWitch
Next lesson: Important InformationMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

SWitch