Skip to content

PHP If...Else...Elseif

PHP Conditional Statements: if, else, elseif

Section titled “PHP Conditional Statements: if, else, elseif”

Conditional statements allow your program to make decisions and execute different blocks of code based on whether specified conditions are true or false.

When writing code, you often need to control the flow of execution based on certain criteria. PHP provides several constructs for this:

  • if statement: Executes a block of code only if a specified condition evaluates to true.
  • if...else statement: Executes one block of code if a condition is true and another block if the condition is false.
  • if...elseif...else statement: Allows checking multiple conditions in sequence. It executes the block associated with the first condition that evaluates to true. An optional else block executes if none of the preceding if or elseif conditions are true.
  • switch statement: Selects one of many blocks of code to be executed based on the value of a single expression. (Covered in the next chapter).
  • Ternary Operator (?:): A shorthand for simple if...else statements.
  • Null Coalescing Operator (??): A shorthand for checking if something exists and is not null, providing a default value otherwise.
  • match expression (PHP 8.0+): A modern alternative to switch with stricter comparisons and expression-based evaluation.

This chapter focuses on if, else, and elseif.

The if statement executes a block of code only when its condition is met (evaluates to true).

if (condition) {
// Code to execute if condition is true
}

The condition is typically an expression that evaluates to a boolean (true or false). PHP automatically converts values to boolean in conditional contexts (e.g., 0, "", null, [] evaluate to false; non-zero numbers, non-empty strings/arrays evaluate to true).

Example: Greeting based on the time of day

<?php
$currentHour = (int) date('G'); // Get current hour in 24-format (as integer)
if ($currentHour < 12) {
echo "Good morning!";
}
if ($currentHour >= 18) {
echo "Good evening!";
}
?>

In this example, “Good morning!” will only be displayed if the script runs before noon. “Good evening!” will only display if it runs at or after 6 PM.

The if...else statement provides an alternative path of execution when the if condition is false.

if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Example: Displaying login/logout status

<?php
$isLoggedIn = false; // Example variable
if ($isLoggedIn) {
echo "Welcome back, User!";
} else {
echo "Please log in to continue.";
}
?>

Here, exactly one of the two messages will be displayed based on the value of $isLoggedIn.

This statement allows you to check multiple conditions sequentially. PHP checks each condition (if, then elseif, then the next elseif, etc.) until it finds one that is true. It executes the block associated with that condition and then skips the rest of the elseif and else blocks.

if (condition1) {
// Code for condition1 being true
} elseif (condition2) {
// Code for condition1 false, condition2 true
} elseif (condition3) {
// Code for condition1/2 false, condition3 true
} else {
// Code if none of the above conditions are true (optional)
}

Example: More detailed time-based greeting

<?php
$currentHour = (int) date('G'); // Get current hour (0-23)
if ($currentHour < 12) {
echo "Good morning!";
} elseif ($currentHour < 18) { // If not < 12, check if < 18
echo "Good afternoon!";
} else { // If not < 12 and not < 18 (i.e., 18 or greater)
echo "Good evening!";
}
?>

This ensures only one greeting is displayed, corresponding to the first matching time range.

PHP also supports an alternative syntax for control structures, often used within HTML templates, replacing curly braces {} with a colon : and ending with endif;, else:, elseif:.

Example:

<?php $userRole = 'editor'; ?>
<?php if ($userRole === 'admin'): ?>
<p>Welcome, Administrator! You have full access.</p>
<?php elseif ($userRole === 'editor'): ?>
<p>Welcome, Editor! You can manage content.</p>
<?php else: ?>
<p>Welcome, Guest!</p>
<?php endif; ?>

While valid, the standard brace syntax {...} is more common in modern PHP code outside of direct HTML templating.

Provides a concise way to assign a value based on a condition.

Syntax: `$variable = (condition) ? value_if_true : value_if_false;`
<?php
$age = 25;
$status = ($age >= 18) ? 'Adult' : 'Minor';
echo "Status: " . $status; // Output: Status: Adult
?>

Provides a default value if a variable is null or does not exist.

Syntax: `$variable = $value_to_check ?? default_value;`
<?php
// Assume $_GET['username'] might or might not be set
$username = $_GET['username'] ?? 'Guest';
echo "Welcome, " . htmlspecialchars($username) . "!";
$config['setting'] = null;
$settingValue = $config['setting'] ?? 'Default Setting';
echo "<br>Setting: " . $settingValue; // Output: Setting: Default Setting
?>

The switch statement, which handles multi-way branching based on a single value, and the match expression (PHP 8.0+), a modern alternative, will be discussed in the next chapter.