Switch to full style
:read: Start PHP with us. Includes topics to help you in php
Post a reply

php switch

Sun Oct 05, 2008 8:16 pm

In switch statement , you can check for many conditions at once .and this is depending on the variable give to the switch .you use switch instead of writing condition in form of if/elseif/elseif/elseif/elseif ... in the next part you will find an example for using switch .


PHP Switch Statement Example


Code:
<?php $number = 1;
echo
"my number is $number<br />";
switch (
$number){
    case
1:
        echo
"your team is  x";
        break;
    case
2:
        echo
"your team is  y";
        break;    
    case
3:
        echo
"your team is  z";
        break;    
    case
4:
        echo
"your team is  e";
        break;
    case
5:
        echo
"your team is  r";
        break;    
}


what you think the output is ? :confused:
the output is
Code:
my number is 1
your team is  x


So, the switch operating work on the $number and search for the case when have same value of $number then execute the segments cross ponding to the case. the break; keyword prevent the other case from being executed .If u didn't write it ,all other cases after the case of correct condition will be executed .

The default case :

It is the case that will be executed when no other cases before it is achieved.

example on default case :


Code:
<?php $number = 132;
echo
"my number is $number<br />";
switch (
$number){
    case
1:
        echo
"your team is  x";
        break;
    case
2:
        echo
"your team is  y";
        break;    
    case
3:
        echo
"your team is  z";
        break;    
    case
4:
        echo
"your team is  e";
        break;
    case
5:
        echo
"your team is  r";
        break;    
      default:
        echo
"your number is not recorded !";
        break;
}


what you think is the output of this code ?

The output is :
Code:
my number is 132
your number is not recorded !




Post a reply
  Related Posts  to : php switch
 Switch vs Hub     -  
 network switch     -  
 JavaScript switch example     -  
 java switch example     -  
 Use Switch with strings     -  
 switch keyword in c++ usage     -  
 switch command for string value     -  
 Java Matrices using a Switch Statement     -  
 Hub-Switch-Router-Proxy-Firewall ?     -  
 restrictions on the values of each case of a switch     -  

Topic Tags

PHP Basics