Conditional logic is one of the most important concepts in PHP. It allows you to control the flow of your program based on different conditions. Whether youβre building a login system, form validation, or dynamic web pages, conditional statements are the foundation.
π― In this guide, youβll learn:
β
How PHP conditional statements work
β
Using if
, else
, and elseif
to control flow
β
Using the switch
statement for multiple cases
β
Ternary and Null Coalescing operators for cleaner code
β
Best practices for writing readable conditional logic
By the end, youβll be able to write efficient conditional logic in PHP like a pro! π
1οΈβ£ What is Conditional Logic?
π‘ Conditional logic allows your PHP program to execute different code depending on specific conditions.
Real-World Examples of Conditionals
β
Login System: "If the password is correct, log in the user."
β
E-commerce Checkout: "If cart total is greater than $100, apply a discount."
β
User Access Control: "If user is an admin, show admin dashboard."
2οΈβ£ The if
Statement (Basic Conditional)
The if
statement runs a block of code only if a condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example: Checking Age for Voting
<?php
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
π‘ Output:
You are eligible to vote.
π₯ How it works?
β
If $age >= 18
, the code inside the if
block runs.
3οΈβ£ The if-else
Statement (Two-way Decision)
π‘ The if-else
statement allows you to handle both true and false cases.
Example: Checking Login Status
<?php
$isLoggedIn = false;
if ($isLoggedIn) {
echo "Welcome, user!";
} else {
echo "Please log in to continue.";
}
?>
π‘ Output:
Please log in to continue.
π₯ How it works?
β
If $isLoggedIn
is true
, the first block runs.
β
If false
, the else
block runs instead.
4οΈβ£ The if-elseif-else
Statement (Multiple Conditions)
π‘ elseif
lets you check multiple conditions in a sequence.
Example: Grading System
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
?>
π‘ Output:
Grade: B
π₯ How it works?
β
Checks each condition in order until it finds one thatβs true.
β
If no condition is met, it falls to the else
block.
5οΈβ£ The switch
Statement (Better for Multiple Choices)
π‘ switch
is great when checking multiple possible values of a variable.
Syntax:
switch (variable) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Code to execute if no match is found
}
Example: Choosing a Subscription Plan
<?php
$plan = "pro";
switch ($plan) {
case "free":
echo "You have limited access.";
break;
case "pro":
echo "You have full access!";
break;
case "enterprise":
echo "You have premium features!";
break;
default:
echo "Invalid plan selected.";
}
?>
π‘ Output:
You have full access!
π₯ Why use switch
instead of multiple if-else
?
β
More readable for multiple cases
β
Faster execution in some cases
6οΈβ£ Ternary Operator (Shorter if-else
)
π‘ The ternary operator is a shorthand for if-else
.
Syntax:
(condition) ? "True case" : "False case";
Example: Checking Login Status
<?php
$isLoggedIn = true;
$message = $isLoggedIn ? "Welcome, user!" : "Please log in.";
echo $message;
?>
π‘ Output:
Welcome, user!
π₯ Why use ternary?
β
Shorter code
β
Great for simple conditions
7οΈβ£ Null Coalescing Operator (??
)
π‘ The null coalescing operator (??
) checks if a variable exists, otherwise it provides a default value.
Example: Checking User Input
<?php
$username = $_GET["user"] ?? "Guest";
echo "Hello, " . $username;
?>
π‘ URL:
http://example.com/?user=ZeroDev
π‘ Output:
Hello, ZeroDev
π₯ If no user
is provided in the URL, it defaults to "Guest"!
8οΈβ£ Combining Conditions with &&
(AND) and ||
(OR)
You can check multiple conditions at once using AND (&&
) and OR (||
).
Example: Checking User Access
<?php
$role = "admin";
$isVerified = true;
if ($role == "admin" && $isVerified) {
echo "Access granted!";
} else {
echo "Access denied.";
}
?>
π‘ Output:
Access granted!
π₯ Explanation:
β
&&
requires both conditions to be true
β
||
requires at least one condition to be true
9οΈβ£ Best Practices for Writing Conditionals
β
Keep conditions simple and readable
β Bad:
if (($age > 18 && $isMember) || (!$isGuest && $plan == "premium")) { ... }
β Good:
$isEligible = ($age > 18 && $isMember) || (!$isGuest && $plan == "premium");
if ($isEligible) { ... }
β
Use switch
when checking multiple values of the same variable
β
Use ternary for short if-else
statements
β
Avoid deep nesting (if
inside if
)
π Final Thoughts
Now you can control the flow of your PHP programs like a pro!
β
Use if-else
for basic conditions
β
Use switch
for multiple cases
β
Use ternary (? :
) for short conditions
β
Use ??
to handle missing values
β
Use &&
(AND) and ||
(OR) for complex conditions
π Next: Mastering PHP Loops
Happy coding! ππ
Hope this is easy enough to understand for new learners.