Conditional Statements in PHP – If/Else/Switch

PHP

Conditional statements are used to test conditions in PHP. You test a certain condition and then perform an action based on the condition. Like when a condition is true do this and when the condition is false, do this instead. These statements make use of the logical as well as comparison operators for forming conditions.

If/Else If/Else

Using this statement, you can check a condition and perform action on whether the condition is true or false. You can further check additional conditions if the first condition turned out to be false.

Example:

<?php
//Just Using IF
$a = 10;
$b = 20;
if($a > $b)
{
echo "A is greater";
}
echo "<br />";
//Using IF...ElSE
if($a > $b)
{
echo "A is greater";
}else{
echo "B is greater";
}
echo "<br />";
//Using IF...Else If...Else
if($a > $b)
{
echo "A is greater";
}else if($a < $b){
echo "B is greater";
}else {
echo "A and B are equal";
}
?>
Output:

B is greater
B is greater

You can combine multiple conditions using logical operators.

Example:

<?php
$a = 1;
$b = 2;
$c = 3;
if($a<$b AND $a<$c){
echo "AND Condition is TRUE";
}
echo "<br />";
if($a<$b OR $a>$c){
echo "OR Condition is TRUE";
}
echo "<br />";
if($a<$b XOR $a>$c){
echo "XOR Condition is TRUE";
}
echo "<br />";
if(!($a>$b)){
echo "NOT Condition is TRUE";
}
?>
Output:
AND Condition is TRUE
OR Condition is TRUE
XOR Condition is TRUE
NOT Condition is TRUE

SWITCH Statement

This statement is also used to perform different actions based on conditions. When the number of conditions are huge or come serially, use this statement.

Example:

<?php
$day = 4;
switch($day){
case 1:
echo "Sunday";
break;
case 2:
echo "Monday";
break;
case 3:
echo "Tuesday";
break;
case 4:
echo "Wednesday";
break;
case 5:
echo "Thursday";
break;
case 6:
echo "Friday";
break;
case 7:
echo "Saturday";
break;
default:
echo "Not a Valid Weekday";
}
?>
Output:
Wednesday
Note: The break; statement is used to escape the condition. You can use it with other conditional or looping statements as well and it will break the execution of the following lines of code.