We can use conditional statements to do different actions based on conditions.
In this guide, we will look into if, if…else, if…elseif…else, switch, and match statements.
The if statement runs some code if one condition is true.
Syntax
if (condition) {
// do something
}
Example
$x = 8;
if ($x > 5) {
echo "You win";
}
// Output: You win
The if…else statement runs some code if a condition is true and another code if that condition is false.
Syntax
if (condition) {
// do something
} else {
// do something else
}
Example
$x = 8;
if ($x > 5) {
echo "Pass";
} else {
echo "Fail";
}
// Output: Pass
The if…elseif…else statement executes different codes for more than two conditions.
Syntax
if (condition 1) {
// do something if condition 1 is true
} elseif (condition 2) {
// cdo something if condition 1 is false and condition 2 is true
} else {
// do something if all conditions are false
}
Example
$x = 4;
if ($x >= 8) {
echo "Great";
} elseif ($x >= 5) {
echo "Good";
} else {
echo "Fail";
}
// Output: Fail
The switch
statement performs different actions based on different conditions.
switch (n) {
case label1:
// do something if n=label1
break;
case label2:
// do something if n=label2
break;
case label3:
// do something if n=label3
break;
default:
// do something if no match is found.
}
Example
$status = "pending";
switch ($status) {
case "paid":
echo "Paid";
break;
case "declined":
echo "Payment declined";
break;
case "pending":
echo "Payment pending";
break;
default:
echo "Unknown status";
}
// Output: Payment pending
We can also use the match()
expression to run code based on the conditions.
In the match expression, we will have to specify all possible cases or use the default
keyword.
The match() statement makes a strict comparison (comparing both value and data type), while the switch() statement only compares value.
$status = 6;
$statusDisplay = match($status) {
1 => "Paid",
2,3 => "Declined",
4 => "Pending",
default => "Unknown",
};
echo $statusDisplay; // Unknown