Monday, December 14, 2009

3:27 AM
By using IF,ELSE,ELSEIF we have to check each and every condition. WIth the use of SWITCH statement you can check for all condiitons at once, and the great thing is that it is actually more efficient programming to do this.


The SWITCH statement takes single value as an input and check all conditions against all the different cases you set up for that SWITCH statement. 


Syntax:


switch (n)
{
  case label1:
    codes to be executed if n=label1;
    break;
  case label2:
    codes to be executed if n=label2;
    break;
  default:
    codes to be executed if n is different from both label1 and label2;
}


First we have a single expression "n"(most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, then the block of code associated with that case is executed.


Use BREAK to prevent the code from running into the next case automatically. The DEFAULT block is executed when there is no match..


Example:


switch ($x)
{
case 20:
  echo "Your age is 20";
  break;
case 21:
  echo "your age is 21";
  break;
case 22:
  echo "Your age is 22";
  break;
default:
  echo "Your age is less than 20 or more than 22";
}

0 comments: