Adscend

Click Here



Click Here

Tuesday

Switch Statement Tutorial

Switch Statement

The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.
Switch case is used to when a condition may have multiple results.
If you want to select one of many blocks of code to be executed, use the Switch statement.
Switch statement is similar to if..else if..else  statement.
The switch statement is used to avoid long blocks of if..else if..else code.


Syntax
switch (expression)
{
case label1:
  code to be executed if expression = label1;
  break;  
case label2:
  code to be executed if expression = label2;
  break;
default:
  code to be executed
  if expression is different 
  from both label1 and label2; 

}

How it works
1. The value of the expression is compared with the values for each case in the structure .
2. If there is a match, the code associated with that case is executed.
3. After a code is executed, break is used to stop the code from running into the next case.
break means, if there is one statement executes, then there is no need to go rest of case statement.
4. The default statement is used if none of the cases are true.
Last case is always default. This is similar to the last else statement.
If none of the above conditions are true, then default will execute.


Example

<script type="text/javascript">
for(var i=1; i<=5; i++)
{
switch(i)
{
case 1:
document.write("when i=1 then case 1 executes <br />");
break;
case 2:
document.write("when i=2 then case 2 executes <br />");
break;
case 3:
document.write("when i=3 then case 3 executes <br />");
break;
default:
document.write("When i=4 then Dedault executes <br />");
break;
}
}
</script>

Output

when i=1 then case 1 executes
when i=2 then case 2 executes
when i=3 then case 3 executes
When i=4 then Dedault executes


No comments:

Post a Comment