PHP Switch Statement with Example

PHP switch statement The PHP switch statement is used to execute one condition from many conditions.It similar to if statements on the same expression. Syntax:
switch(n)
{
            case1:
statement if n=case1;
break;
            case2:
            statement if n=case2;
break;
            case3:
            statement if n=case3;
break;
              ...
default:
statement if n is different from all labels;
}
Working: First you have a single expression “n” (most frequently a variable), that is evaluated once. The value of the expression is compared with the values for each case in the structure. If any match found, the block of code associated with will be executed. Use break to prevent the code from executing into the next case automatically. The default statements is used if no match is found. PHP Switch Statement Flow Chart Example:
<?php
$num=30;   
switch($num){   
case 10:   
echo("number is equals to 10");   
break;   
case 20:   
echo("number is equal to 20");   
break;   
case 30:   
echo("number is equal to 30");   
break;   
default:   
echo("number is not equal to 10, 20 or 30");   
}  
?>
Output:                
number is equal to 30
Example2:
<?php
$today = date("D");
switch($today){
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 "Not Found.";
break;
}
?>
Output:
Today is Thursday.
Example3:
<?php
$num = 1;
switch ($num)
 {
case 1: echo 'The number is 1!';
break;
case 2: echo 'The number is 2';
break;
default: echo 'Unknown number';
}
?>
Output:
The number is 1!
Operator Description Example
<  Less than ($age < 18)
>  Greater than ($age > 18)
<= Less than or equal to ($age <= 18)
>= Greater than or equal to ($age >= 18)
!= Not equal to ($age != 18)
== Equal to ($age == 18)
Example4:
<?php
$age = 21;
switch ($age)
{
case 17: echo 'You\'re not old enough to play GTA!';
break;
case 17: echo 'You\'re old enough to drive!';
break;
case 18: echo 'You\'re old enough to play GTA!';
break;
case ($age > 18): echo 'You\'re quite old!';
break;
default: echo 'Was that a number?';
}
?>
Output:
You're quite old!
Example5:
<?php
extract($_POST);
if(isset($save))
{
switch($ch)
{
case 'ADD(+)':
$res=$fn+$sn;
break;
case 'SUB(-)':
$res=$fn-$sn;
break;
case 'MUL(*)':
$res=$fn*$sn;
break;
case 'DIV(/)':
$res=$fn*$sn;
}
}
?>
<form method="post">
<table align="center">
<tr>
<th> Enter First Number</th>
<th><input type="number" name="fn" value="<?php  echo @$fn;?>"/></th>
</tr>
<tr>
<th> Enter Second Number</th>
<th><input type="number" name="sn" value="<?php  echo @$sn;?>"/></th>
</tr>
<tr>
<th>Select Your Choice</th>
<th>
<select name="ch">
<option>ADD(+)</option>
<option>SUB(-)</option>
<option>MUL(*)</option>
<option>DIV(/)</option>
</select>
</th>
</tr>
<tr>
<th>Your Result</th>
<th><input type="number" readonly="readonly" disabled="disabled"
value="<?php  echo @$res;?>"/></th>
</tr>
<tr>
<thcolspan="2">
<input type="submit" name="save" value="Show Result"/>
</th>
</tr>
</table>
</form>
Output: PHP Switch Statement example

Related Topics

PHP is_iterable() Function

The is_iterable() function in PHP verifies that the contents of the specified variable is an iterable value. Syntax is_iterable ( mixed $var ) var(required)- This parameter represents the value to check. Return This function returns a Boolean value TRUE if the parameter var is iterable, else it returns...

1 minute read.

PHP pos() Function

PHP pos() Function The pos() function in PHP returns the current element in an array which is initialized to the first element of the array. This function is an alias of current(). Syntax pos ( array...

1 minute read.

PHP chop() Function

PHP chop() Function The chop() function in PHP removes whitespaces or other predefined characters from the right end of the specified string. Syntax chop(str,charlist) Parameter str(required)- This parameter specifies the string to check. charlist(optional)- This parameter...

1 minute read.

PHP For Loops

PHP for loop is used when the specified condition is predefined. Syntax: for (initialization; condition; increment/decrement ) { code to be executed; } Example <!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php echo " Print counting using for loop"."<br>"; for($i=1;$i<=5;$i++){ echo $i."<br>"; } ?> </body> </html> Output Print counting using...

1 minute read.

PHP str_repeat() Function

PHP str_repeat() Function The str_repeat() function in PHP repeats a string a specified number of times. Syntax str_repeat ( string $input , int $multiplier ) Parameter string(required)- This parameter signifies the string to be repeated. multiplier(required)- This parameter represents the number of times the string will be...

1 minute read.

PHP strrrev() Function

PHP strrrev () Function The strrev() function in PHP reverses a string. Syntax strrev ( string $string ) Parameter string(required)- This parameter represents the input string to be reversed. Return This function returns the reversed string. Example 1 Output Initial string: Hello...

1 minute read.

PHP sha1_file() Function

PHP sha1_file() Function The sha1_file() in PHP calculates the sha1 hash of a file and returns the hash (40-character hexadecimal number). Syntax sha1_file ( string $filename [, bool $raw_output] )  Parameter filename(required)- This parameter represents the filename of the file to hash. raw_output(optional)- This...

1 minute read.

PHP doubleval() Function

PHP doubleval() Function The doubleval() function in PHP is used to give the float value of a variable. This function is an alias of floatval(). Syntax doubleval ( mixed $var ) Parameter var(required)- This parameter represents the name of the variable that...

1 minute read.

PHP shuffle() Function

PHP shuffle() Function The shuffle() function in PHP shuffles an array in a random array. Syntax shuffle ( array &$array )  Parameter array(required)- This parameter represents the input array.  Return This parameter returns a Boolean value TRUE on success or FALSE on failure. Example 1 Output Original Array: Array ...

1 minute read.

PHP strnatcasecmp() Function

PHP strnatcasecmp() Function The strnatcasecmp() function in PHP compares two strings using a "natural" algorithm. It is a case-insensitive function. Syntax strnatcasecmp ( string $str1 , string $str2 )  Parameter str1(required)- This parameter represents the first string. str2(required)- This parameter represents the second string. Return This function returns a value less...

1 minute read.

PHP Associative Arrays

PHP associate array is used to access the elements with keys by “=>” symbol. There are two ways to create an associative array. 1st way: $age = array("John"=>"20", "Helena"=>"30", "Rasmus"=>"29"); 2nd way: $age['john'] = "20"; $age['Helena'] =...

1 minute read.

PHP str_rot13() Function

PHP str_rot13() Function The str_rot13() function in PHP performs the ROT13 encoding on a string and returns the resulting string. The ROT13 encoding is used to shift every letter by 13 places in the alphabet...

1 minute read.

PHP array_intersect_uassoc() function

The array_intersect_uassoc () function in PHP is used to compute the intersection of arrays with the help of an additional index check, comparing indexes by a callable function. It returns an array containing...

1 minute read.

PHP range() Function

PHP range() Function The range () function in PHP is used to create an array containing a range of elements. Syntax range ( mixed $start , mixed $end [, number $step = 1 ] ) Parameter start(required)- This parameter represents the first value of the sequence. end(required)- This parameter represents the...

1 minute read.

PHP sprintf() Function

PHP sprintf() Function The sprintf() function in PHP is used to write a formatted string to a variable and returns a formatted string. PHP 4 and above versions support the sprintf() function. The related functions are...

8 minutes read.

PHP array_flip() function

PHP array_flip() function The array_flip() function in PHP exchanges all keys with their associated values in an array and returns an array in flip order. If the specified value has several occurrences, the latest key will be...

1 minute read.

PHP bin2hex() Function | Convert Binary to Hexadecimal

PHP bin2hex() Function The bin2hex() function in PHP converts the specified string value of ASCII characters to hexadecimal value. Syntax bin2hex(str) Parameter str(Required): This parameter represents the string to be converted into hexadecimal. Return  This function returns...

1 minute read.

PHP array_key_exists() function

The array_key_exists () function in PHP is used to check whether the specified key exists in the array or not. It returns a Boolean value TRUE if the given key exists else it returns FALSE. Syntax array_key_exists(mixed key,array$array) Parameter key(required)- This...

1 minute read.

PHP Tutorial

PHP Tutorial PHP Introduction PHP is a server-side scripting language which is used for web development. It stands for Hypertext Preprocessor. It is faster than another programming language. It supports multiple databases like MySQL, SQL, PostgreSQL and...

3 minutes read.

PHP print() Function

PHP print() Function The print() function in PHP is used to output one or more string. Syntax print ( string $arg ) Parameter arg(required)- This parameter represents the input data. It can take one or more arguments. Return This function returns an integer value 1. Example...

1 minute read.