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 sscanf() Function

PHP sscanf() Function The sscanf() function in PHP parses input from a string according to a given format. Syntax sscanf ( string $str , string $format [,mixed &$arg1,$agr2,$arg++... ] ) Parameter str(required)- This parameter specifies the string to read. format(required)- This parameter specifies the format to use. The conversion specification...

3 minutes read.

PHP vfprintf() Function

PHP vfprintf() Function The vfprintf() function in PHP writes a formatted string to a specified output stream. Syntax vfprintf ( resource $handle , string $format , array $args )  Parameter handle(required)- This parameter represents where to write the string. format(required)- This parameter specifies the string and how to format the...

3 minutes read.

PHP strtoupper() Function

The strtoupper() function in PHP is used to convert a string to uppercase. This function is binary-safe. The related functions are as follows: strtolower()lcfirst()ucfirst()ucwords() Syntax strtoupper ( string $string ) Parameter string(required)- This parameter represents the input string. Return This function returns a string with all alphabetic...

1 minute read.

PHP ucfirst() Function

PHP ucfirst() Function The ucfirst() function in PHP converts the first character of the specified string to uppercase. Syntax ucfirst ( string $str ) Parameter str(required)- This parameter represents the input string. Return This function returns a string with the first character of the specified string capitalized if that...

1 minute read.

PHP quoted_printable_encode() Function

PHP quoted_printable_encode() Function The quoted_printable_encode() function in PHP converts a 8 bit string to a quoted-printable string. This function is similar to imap_8bit(), except this one does not require the IMAP module to work. Syntax quoted_printable_encode ( string $str ) Parameter str(required)- This parameter represents...

1 minute read.

PHP is_numeric() Function

The is_numeric() function in PHP finds whether the specified variable is a number or a numeric string. It returns a Boolean value TRUE if the specified var is a number or a numeric string else it returns FALSE otherwise. Syntax is_numeric ( mixed...

1 minute read.

PHP Array Functions

There are various array functions in PHP. They are used to access and manipulate the elements ofan array. Following are functions of array. Array Function Description array() It is used to create an array. array_change_key_case() It is...

3 minutes read.

PHP array_slice() Function

PHP array_slice() Function The array_slice() function in PHP is used to extract a slice of the array. It returns the sequence of elements from the array as specified by the offset and length parameters. Syntax array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) Parameter array(required)- This array represents the...

2 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 is_string() Function

PHP is_string() Function The is_ string() function in PHP finds whether a variable is a string or not. It returns a Boolean value TRUE if the parameter var is string, else it returns FALSE. Syntax is_string ( mixed $var ) Parameter var(required)- This parameter represents...

1 minute read.

PHP array_intersect_assoc() function

PHP array_intersect_assoc() function The array_intersect_assoc() function in PHP is used to compute the intersection of arrays with the help of an additional index check. It returns an array containing all the entries from array1 that are present...

1 minute read.

PHP is_integer() Function

The PHP is_integer() function in PHP is used to  find whether a variable is an integer or not. It returns a Boolean value true if the parameter var is integer else it returns...

1 minute read.

PHP crypt() Function

PHP crypt() Function The crypt () function in PHP returns a hashed string using DES, Blowfish, or MD5 algorithms. Some constants of crypt() function are as follows: [CRYPT_STD_DES][CRYPT_EXT_DES][CRYPT_MD5][CRYPT_BLOWFISH][CRYPT_SHA_256][CRYPT_SHA_512] etc. Syntax crypt ( string $str [, string $salt ] )  Parameter str(required)- This parameter represents the string to be hashed salt(optional)- This parameter...

2 minutes read.

PHP current() function

PHP current() function The current() function in PHP returns the current element in an array, which is initialized to the first element inserted into the array. Syntax current ( array $array )   Parameter array (required)– This parameter represents the input array or countable object. Return This...

1 minute read.

PHP get_defined_vars() Function

PHP get_defined_vars() Function The get_defined_vars() function in PHP returns an array of all defined variables. It returns a multidimensional array containing a list of all defined variables. Syntax get_defined_vars ( void ) Parameter NA Return This function returns a multidimensional array containing a list...

1 minute read.

Python main() function

What is a main() function? In most of the programming languages, there is this one special function i.e., main() which is executed firstly everytime when we run the program. The special...

6 minutes read.

PHP strtr() Function

PHP strtr() Function The strtr() function in PHP translates or replaces certain characters in a string. Syntax strtr ( string $str , string $from , string $to ) or strtr ( string $str , array $replace_pairs ) Parameter str(required)- This parameter specifies the string to translate from(required)- This parameter represents the string being translated to the parameter ‘to’. to(required)- It specifies what...

1 minute read.

PHP key() Function

PHP key() Function The key() function in PHP fetches a key from an array and returns the index element of the current array position. Syntax key ( array $array ) Parameter array(required)- This parameter represents the input array. Return This function returns the key of the...

1 minute read.

PHP nl2br() Function

PHP nl2br() Function The nl2br() function in PHP inserts HTML line breaks before all newlines in a string. Syntax nl2br ( string $string [, bool $is_xhtml] ) Parameter sting(required)- This parameter specifies the input string. is_xhtml(optional)- This parameter states whether to use XHTML compatible line breaks...

1 minute read.

PHP Example

We can create a simple program by writing the source code inside the php tag and save it with .php extension. Syntax: <?php // your code here ?> Let us take an example of PHP. <!DOCTYPE html> <html> <head>            ...

1 minute read.