PHP Switch Statement Examples

by Hiroshi on June 20, 2008

in PHP Basics, Switch

With the use of the switch statement you can check for many conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation! The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

Consider following examples to understand switch.

<?php
$v1 = "Javed";
$v2 = "Usman";
$v3 = "Kamran";
$v4 = "Azhar";
 
switch($v1)
{
case "Javed":
echo "Javed is a friend";
break;
case "Usman":
echo "Usman is working";
break;
case "Kamran":
echo "Kamran is not good";
break;
default:
echo "Nothing to tell you";
}
// output: Javed is a friend
?>
<?php
$s1 = 1;
$s2 = 2;
$s3 = 3;
 
switch($s1)
{
case 1:
echo "Ongoing case is 1";
break;
 
case 2:
echo "Ongoing case is 2";
break;
 
case 3:
echo "Ongoing case is 3";
break;
 
default:
echo "No Case";
}
// output: Ongoing case is 1
?>

Switch Example With Form Input

Consider
Javed, Usman, Sarfraz, Aubi are friends while Hitler, John and Smith are not.
We have page name as switch_with_form.php
And we have register_globals are on in php.ini
(You can create two pages if you want, one for form and other for script)

Form Code

Describe your name for identification:
<form action="switch_with_form.php" method="post">
<input type="text" name="name">
<input type="submit" name="Submit" value="Submit">
</form>

PHP Code

<?php
if($name)
{
switch ($name) {
  case "javed":
  case "usman":
  case "sarfraz":
  case "aubi":
    echo "<b><font color=blue> Welcome, my dear, $name ,you are my friend </font></b>";
    break;
  case "hitler":
  case "john":
  case "smith":
    echo "<b><font color=red> Hey, You are no friend of mine, $name </font></b>";
    break;
  default:
    echo "<b> I do not know who you are, Mr. $name , Go away </b>";
}
}
?>

Result

For Aubi, Sarfraz, Usman and Javed input message “Welcome, my dear, provided name ,you are my friend” will be appeared and for Hitler, John and Smith a message “Hey, You are no friend of mine, provided name” will be appeared.
For any other input third message “I do not know who you are, Mr. provided name , Go away” will be displayed.

PHP Switch Examples Download

Related Posts

Previous post:

Next post: