PHP is one of the most popular server-side languages for web development. Essential for generating dynamic content is “conditional branching.” This article explains the overview, basic syntax, and commonly used code examples step-by-step for beginners. By running actual sample code, you will learn how to build process flows in PHP.
What is Conditional Branching in PHP? Basic Overview and Use Cases
Conditional branching controls the flow of a program by switching processes according to certain conditions. This enables returning different results based on user status or input, making web applications interactive.
For example:
- Switching displayed content based on whether a user is logged in
- Showing error messages during form input validation
- Displaying or hiding the purchase button depending on product stock status
- Displaying a banner only on specific pages
Conditional branching in PHP is an essential basic technique to create these dynamic features.
Basic Syntax and Sample Code of the if Statement
The simplest conditional branching is the if
statement. If the if
condition is true, the code block inside executes. If false, it is skipped.
<?php
$user_logged_in = true; // Flag indicating login status
if ($user_logged_in) {
echo "Welcome, user!"; // Displayed if condition is true
} else {
echo "Please log in."; // Displayed if condition is false
}
?>
if (condition) { … }
: Code executed when the condition is trueelse { … }
: Code executed when the condition is falseelseif (another condition) { … }
: Used to check multiple conditions in sequence
Example of elseif
<?php
$score = 75;
if ($score >= 90) {
echo "Grade is A";
} elseif ($score >= 70) {
echo "Grade is B";
} else {
echo "Grade is C or below";
}
?>
As shown, conditions are evaluated step-by-step and the first true condition is executed.
How to Write Complex Conditional Branching with switch Statement
The switch
statement is suitable for branching multiple cases based on the same variable’s value. You write the process for each case
, use break
to end that process, and write the process for unmatched cases under default
.
<?php
$role = 'editor'; // User role stored as a string
switch ($role) {
case 'admin':
echo "Displaying admin menu.";
break;
case 'editor':
echo "Displaying editor menu.";
break;
case 'subscriber':
echo "Displaying read-only menu.";
break;
default:
echo "Unknown role.";
break;
}
?>
- Always write
break;
to prevent fall-through. default
handles cases where none of thecase
s match.
Examples and Cautions in Conditional Branching
Combining Multiple Conditions
You can combine conditions using logical operators. The main operators are as follows.
&&
(AND) – True if both conditions are true||
(OR) – True if either condition is true!
(NOT) – Negates the truth value of a condition
Example of AND (&&)
<?php
$age = 20; // Assign 20 to the age variable
$has_ticket = true; // Boolean variable representing ticket possession (true means has ticket)
// Conditional branch: Admission allowed if age is 18 or older AND has a ticket
if ($age >= 18 && $has_ticket) {
echo "Admission allowed"; // Output if condition is met
} else {
echo "Admission denied"; // Output if condition is not met
}
?>
Example of OR (||)
<?php
$is_admin = false; // Variable indicating admin rights (false: no rights)
$is_moderator = true; // Variable indicating moderator rights (true: has rights)
// Conditional branch: Executes if user has admin or moderator rights
if ($is_admin || $is_moderator) {
echo "You have admin or moderator rights"; // Displayed if either is true
} else {
echo "No rights"; // Displayed if both are false
}
?>
Example of NOT (!)
<?php
$is_logged_in = false; // Variable indicating login status (false: not logged in)
// Conditional branch: Executes if not logged in ($is_logged_in is false)
if (!$is_logged_in) {
echo "Please log in"; // Display message if not logged in
} else {
echo "Welcome!"; // Display welcome message if logged in
}
?>
Nested Conditional Branching
You can write conditional branches inside other conditions.
<?php
$score = 85; // Assign score 85 to variable $score
// First, check if the score is 60 or above
if ($score >= 60) {
// If 60 or above, further check if it is 90 or above
if ($score >= 90) {
// If 90 or above, display "Excellent"
echo "Excellent";
} else {
// If below 90 (but 60 or above), display "Good"
echo "Good";
}
} else {
// If below 60, display "Fail"
echo "Fail";
}
?>
Caution: Be Careful with Type Differences
Because PHP automatically converts types, you need to be careful about the difference between ==
(equality operator) and ===
(strict comparison operator).
<?php
var_dump(0 == false); // true
var_dump(0 === false); // false
?>
However, since ===
compares type strictly, it can sometimes lead to unintended behavior. Especially when handling user input that requires flexible checking, using ==
can be easier, so it is important to use them appropriately.
Writing Concise Conditional Branching with the Ternary Operator
The ternary operator is a shorthand for if-else
statements, allowing you to switch values in one line. It is convenient for use inside expressions and when you want to keep your code simple.
Basic Syntax
(condition) ? (value if true) : (value if false);
Sample Code
<?php
$user_logged_in = true;
// Regular if-else statement
if ($user_logged_in) {
$message = "Welcome, user!";
} else {
$message = "Please log in.";
}
echo $message;
// Using the ternary operator
$message = $user_logged_in ? "Welcome, user!" : "Please log in.";
echo $message;
?>
The ternary operator is especially useful when assigning values to variables, allowing you to write shorter and more readable code.
Nesting the Ternary Operator
When dealing with multiple conditions, you can nest ternary operators, but be careful not to overuse them to maintain readability.
<?php
$score = 75;
$result = ($score >= 90) ? "Grade is A" :
(($score >= 70) ? "Grade is B" : "Grade is C or below");
echo $result;
?>
Advantages and Disadvantages of the Ternary Operator
- Advantages
- Can be written short and simple
- Can be used inside expressions, making it useful for variable assignment and function arguments
- Disadvantages
- Becomes hard to read when nesting complex conditions
- For complex processing, it is safer to use
if-else
statements instead of ternary operators
The ternary operator is one of the handy ways to write PHP used daily. Be sure to identify when to use it to write smart code.
Summary
Conditional branching in PHP is a fundamental technique for controlling program flow and is indispensable for developing dynamic websites and web applications. Mastering if
and switch
statements and organizing complex conditions will enable you to implement more advanced processing.
First, try the sample code in this article to deepen your understanding by actually running the code.