PHP Basics

PHP Switch Case

If we have more than one tasks to executed depending upon conditions, then in such case we use switch statement in php.

Switch

To better understand the usage of Switch, lets consider following example.

Example

print value of the variable.

<?php

$num=4;

if($num==0){

echo “The value of num is 0”;

}elseif($num==1){

echo “The value of num is 1”;

}elseif($num==2){

echo “The value of num is 2”;

}elseif($num==3){

echo “The value of num is 3”;

}elseif($num==4){

echo “The value of num is 4”;

}elseif($num==5){

echo “The value of num is 5”;

}

 

?>

Output: The value of num is 4

The same result can be achieved using switch statement in php

Syntax

<?php

switch(value){

case 1: //code to execute task

break;

case 2: //code to execute task

break;

case 3: //code to execute task

break;

case 4: //code to execute task

break;

.

.

.

case n: //code to execute task

break;

}

?>

Lets see how can we use switch statement in the above example.

<?php

$num=4;

switch($num){

case 0: echo “The value of num is 0”;

break;

case 1: echo “The value of num is 1”;

break;

case 2: echo “The value of num is 2”;

break;

case 3: echo “The value of num is 3”;

break;

case 4: echo “The value of num is 4”;

break;

case 5: echo “The value of num is 5”;

break;

}

?>

Output: The value of num is 4