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.
PHP Conditional Constructs
Section titled “PHP Conditional Constructs”When writing code, you often need to control the flow of execution based on certain criteria. PHP provides several constructs for this:
ifstatement: Executes a block of code only if a specified condition evaluates totrue.if...elsestatement: Executes one block of code if a condition istrueand another block if the condition isfalse.if...elseif...elsestatement: Allows checking multiple conditions in sequence. It executes the block associated with the first condition that evaluates totrue. An optionalelseblock executes if none of the precedingiforelseifconditions aretrue.switchstatement: 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 simpleif...elsestatements. - Null Coalescing Operator (
??): A shorthand for checking if something exists and is notnull, providing a default value otherwise. matchexpression (PHP 8.0+): A modern alternative toswitchwith stricter comparisons and expression-based evaluation.
This chapter focuses on if, else, and elseif.
The if Statement
Section titled “The if Statement”The if statement executes a block of code only when its condition is met (evaluates to true).
Syntax:
Section titled “Syntax:”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
Section titled “The if...else Statement”The if...else statement provides an alternative path of execution when the if condition is false.
Syntax:
Section titled “Syntax:”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.
The if...elseif...else Statement
Section titled “The if...elseif...else Statement”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.
Syntax:
Section titled “Syntax:”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.
Alternative Syntax (Less Common)
Section titled “Alternative Syntax (Less Common)”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.
Shorthand Conditionals
Section titled “Shorthand Conditionals”Ternary Operator (?:)
Section titled “Ternary Operator (?:)”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?>Null Coalescing Operator (??)
Section titled “Null Coalescing Operator (??)”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?>Next Steps
Section titled “Next Steps”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.