- 5 years ago
- Zaid Bin Khalid
- 11,213 Views
-
10
In this tutorial, you will figure out how to utilize the switch-case statement and if-else statement with the same problem. The PHP if-else and switch and case controllers details are given below.
PHP If… Else Vs Switch… Case
A switch-case condition is an option to the if-elseif-else explanation, which does nearly something very similar. The switch-body of evidence articulation tests a variable against a progression of qualities until it finds a match, and afterward executes the square of code relating to that coordinate.
<?php
$n = 1;
switch($n){
case 1:
echo 'We find the number<br />';
//break;
case 2:
echo 'We find next number<br />';
//break;
default:
echo 'Default number';
}
?>
The above code will return the below output.
We find the number
We find next number
Default number
If you want to break the code just after get your desire result use the break statement of PHP as shown in the below code.
<?php
$n = 1;
switch($n){
case 1:
echo 'We find the number';
break;
case 2:
echo 'We find next number';
break;
}
?>
The switch-case explanation varies from the if-elseif-else statement in one significant manner. The switch explanation executes line by line and once PHP finds a case and gets true it is not only read that condition but additionally read all the cases. That is why we need a break statement to exit further execution. But in if-elseif statement one, you find the true condition code does not execute further. To understand the better way see the below example.
<?php
$today = date("D");
switch($today){
case "Sun":
echo "Today is Sunday";
break;
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;
}
?>
The above example is the switch-case example you can do the same logic with if-elseif-else controllers but in the if-elseif-else statement, you don’t need to add break statement. So, see the below example to understand the same case with the if-elseif-else statement.
<?php
//The if else statement
if($today=="Sun"){
echo 'Today is sunday.';
}elseif($today=="Mon"){
echo 'Today is Monday.';
}
?>
The above examples explain the real difference between the if-elseif-else and switch-case statements in PHP and their usage.
- 5 years ago
- Zaid Bin Khalid
- 11,213 Views
-
10