Skip to content

PHP Conditional Statements

Conditional statements execute different code blocks based on conditions, enabling dynamic decision-making in your applications.


Executes code only when a condition is true.

$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
// Multiple conditions
if ($score >= 80 && $attendance >= 85) {
echo "Excellent performance!";
}

Provides an alternative when the condition is false.

$temperature = 15;
if ($temperature > 25) {
echo "It's hot outside.";
} else {
echo "It's cool outside.";
}

Checks multiple conditions in sequence.

$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}

Cleaner alternative to multiple elseif when checking one variable against multiple values.

$orderStatus = "shipped";
switch ($orderStatus) {
case "pending":
echo "Order is being processed.";
break;
case "shipped":
echo "Order is on the way!";
break;
case "delivered":
echo "Order has been delivered.";
break;
default:
echo "Unknown status.";
}

Important: Always use break to prevent fall-through.


A more concise alternative to switch that returns a value directly.

$orderStatus = "shipped";
$message = match($orderStatus) {
"pending" => "Order is being processed.",
"shipped" => "Order is on the way!",
"delivered" => "Order has been delivered.",
default => "Unknown status."
};
echo $message;

You can also match multiple values:

$day = "Saturday";
$type = match($day) {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday" => "Weekday",
"Saturday", "Sunday" => "Weekend",
};

Unlike switch, match uses strict comparison (===) and throws an UnhandledMatchError if no match is found and no default is provided.


Shorthand for simple if-else assignments.

$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
// Equivalent to:
if ($age >= 18) {
$status = "Adult";
} else {
$status = "Minor";
}

Returns the first non-null value; useful for handling undefined variables.

// Replaces isset() ternary
$username = $_GET['username'] ?? 'Guest';
// Chain multiple fallbacks
$config = $userConfig ?? $defaultConfig ?? 'fallback';

  1. Use strict comparison (===) to avoid type coercion bugs.

  2. Extract complex conditions into variables for readability.

// Harder to read
if ($user['age'] >= 18 && $user['verified'] && $user['status'] !== 'banned') { }
// Better
$canAccess = $user['age'] >= 18 && $user['verified'] && $user['status'] !== 'banned';
if ($canAccess) { }
  1. Use switch for multiple value checks instead of many elseif statements.

  2. Avoid deep nesting: use early returns or logical operators.

  3. Use ternary only for simple assignments: don’t nest ternary operators.