codescracker


php

PHP switch



« Previous Tutorial Next Tutorial »


PHP switch statement is basically used to perform different actions based on different conditions provided.

PHP switch statement is used to select one of many blocks of code to be executed. Here is the general form to use switch statement in PHP:

switch(expression)
{
case this1:
code to be executed here, if expression = this1;
break;  
case this2:
code to be executed here, if expression = this2;
break;
default:
code to be executed here,
if expression is different 
from both this1 and this2;
}

PHP switch Example

Let's take an example that demonstrates the switch case in PHP.

<!DOCTYPE html>
<html>
<head>
<title>PHP switch Case Example - CodesCracker</title>
</head>
<body>
<?php
$var = 4;
// first switch case
switch($var)
{
case 1:
echo "The value is 1";
break;
case 2:
echo "The value is 2";
break;
case 3:
echo "The value is 3";
break;
case 4:
echo "The value is 4";
break;
case 5:
echo "The value is 5";
break;
default:
echo "The value is unknown";
break;
}
echo "<br/>";

$var = "Codes";
// second switch
switch($var)
{
case "PHP":
echo "The word is PHP";
break;
case "Switch":
echo "The word is Switch";
break;
case "Codes":
echo "The word is Codes";
break;
case "Cracker":
echo "The word is Cracker";
break;
case "Case":
echo "The word is Case";
break;
default:
echo "The word is not known";
break;
}
?>
</body>
</html>

Here is the sample output produced by the above switch case example code in PHP.

php switch

Here is another example, uses switch statement in PHP:

<!DOCTYPE html>
<html>
<head>
<title>PHP switch Case - CodesCracker</title>
</head>
<body>
<h2>Checking for the Day</h2>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>

Here is the output of the above PHP script:

PHP Switch Statement

« Previous Tutorial Next Tutorial »


Latest 5 Posts by CodesCracker




Tools
Calculator

Quick Links
Signup - Login - Give Online Test