PHP Conditionals
Conditionals are a fundamental part of programming. They allow your code to make decisions based on whether something is true or false.
In PHP, conditionals are commonly written using if, else, and elseif. You can also use
switch, match, ternary operators, and null coalescing operators depending on the situation.
A conditional asks a question, such as:
- Is this user logged in?
- Is the total greater than 100?
- Does this variable contain a value?
- Which role does this user have?
Based on the answer, PHP runs one block of code and skips the others.
Basic If Statement
The simplest conditional is an if statement. It runs code only when the condition is true.
<?php
$age = 18;
if ($age >= 18) {
echo "You are old enough to vote.";
}
?>
Expected output:
You are old enough to vote.
In this example, PHP checks whether $age is greater than or equal to 18.
Since it is, the message is displayed.
If / Else Conditionals
An else block lets you provide a fallback when the original condition is false.
<?php
$age = 16;
if ($age >= 18) {
echo "You are old enough to vote.";
} else {
echo "You are not old enough to vote yet.";
}
?>
Expected output:
You are not old enough to vote yet.
Since $age is less than 18, the if block is skipped and the else block runs instead.
If / Elseif / Else
When you need to check multiple conditions, use elseif.
<?php
$score = 87;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: Needs work";
}
?>
Expected output:
Grade: B
PHP checks each condition from top to bottom. Once it finds a condition that is true, it runs that block and skips the rest.
Comparison Operators
Conditional statements often use comparison operators. These operators compare two values.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | $name == "Travis" |
=== |
Identical to, including type | $age === 18 |
!= |
Not equal to | $status != "closed" |
!== |
Not identical to | $id !== "5" |
> |
Greater than | $total > 100 |
< |
Less than | $total < 100 |
>= |
Greater than or equal to | $score >= 70 |
<= |
Less than or equal to | $quantity <= 10 |
Using Strict Comparisons
In PHP, == checks whether two values are equal, but === checks whether they are equal and the same type.
In most cases, === is safer and more predictable.
<?php
$value = "5";
if ($value == 5) {
echo "Equal using ==";
}
if ($value === 5) {
echo "Equal using ===";
}
?>
The first condition is true because PHP treats the string "5" and the number 5 as equal.
The second condition is false because one value is a string and the other is an integer.
Logical Operators
Logical operators let you combine multiple conditions.
| Operator | Meaning | Example |
|---|---|---|
&& |
And | $age >= 18 && $registered === true |
|| |
Or | $role === "admin" || $role === "manager" |
! |
Not | !$loggedIn |
Example Using And
<?php
$age = 21;
$hasTicket = true;
if ($age >= 18 && $hasTicket === true) {
echo "You may enter.";
} else {
echo "You may not enter.";
}
?>
Expected output:
You may enter.
Example Using Or
<?php
$role = "manager";
if ($role === "admin" || $role === "manager") {
echo "You can access this page.";
} else {
echo "Access denied.";
}
?>
Expected output:
You can access this page.
Checking Boolean Values
A boolean value is either true or false. You will often use booleans for things like login status,
feature settings, permissions, and yes/no values.
<?php
$isLoggedIn = true;
if ($isLoggedIn) {
echo "Welcome back!";
} else {
echo "Please log in.";
}
?>
Expected output:
Welcome back!
Since $isLoggedIn is already true or false, you do not need to write $isLoggedIn === true,
although doing so is sometimes useful when you want to be extra clear.
Checking Empty Values
PHP has a function called empty() that checks whether a value is empty.
This is useful when working with forms, user input, or optional data.
<?php
$name = "";
if (empty($name)) {
echo "Name is required.";
} else {
echo "Hello, " . $name;
}
?>
Expected output:
Name is required.
Values such as an empty string, 0, "0", null, false, and an empty array are considered empty.
Checking Whether a Variable Exists
The isset() function checks whether a variable exists and is not null.
<?php
$username = "admin";
if (isset($username)) {
echo "Username is set.";
} else {
echo "Username is missing.";
}
?>
Expected output:
Username is set.
isset() is commonly used when checking form values, query string values, array keys, and optional variables.
Conditionals with Form Data
A common use for conditionals is checking submitted form data.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST["email"] ?? "";
if (empty($email)) {
echo "Email address is required.";
} else {
echo "Thank you for submitting your email.";
}
}
?>
In this example, PHP first checks whether the request method is POST. Then it checks whether the email field is empty.
Nested Conditionals
You can place one conditional inside another. This is called nesting.
<?php
$isLoggedIn = true;
$role = "admin";
if ($isLoggedIn) {
if ($role === "admin") {
echo "Welcome to the admin dashboard.";
} else {
echo "Welcome to your account.";
}
} else {
echo "Please log in.";
}
?>
Expected output:
Welcome to the admin dashboard.
Nested conditionals are useful, but too many levels can make your code difficult to read. If your conditionals are getting deeply nested, consider simplifying your logic.
Switch Statements
A switch statement is useful when you want to compare one value against several possible options.
<?php
$status = "pending";
switch ($status) {
case "pending":
echo "Your order is pending.";
break;
case "paid":
echo "Your order has been paid.";
break;
case "shipped":
echo "Your order has shipped.";
break;
case "cancelled":
echo "Your order was cancelled.";
break;
default:
echo "Unknown order status.";
break;
}
?>
Expected output:
Your order is pending.
The break statement tells PHP to stop running the switch after it finds a matching case.
Without break, PHP may continue into the next case.
Match Expressions
PHP 8 introduced match, which is similar to switch but shorter and stricter.
<?php
$status = "paid";
$message = match ($status) {
"pending" => "Your order is pending.",
"paid" => "Your order has been paid.",
"shipped" => "Your order has shipped.",
"cancelled" => "Your order was cancelled.",
default => "Unknown order status.",
};
echo $message;
?>
Expected output:
Your order has been paid.
A match expression returns a value. It also uses strict comparison, which makes it more predictable than a traditional
switch statement.
Ternary Operator
The ternary operator is a shorter way to write a simple if / else statement.
<?php $age = 20; $message = $age >= 18 ? "Adult" : "Minor"; echo $message; ?>
Expected output:
Adult
This line:
$message = $age >= 18 ? "Adult" : "Minor";
means:
- If
$age >= 18is true, use"Adult". - Otherwise, use
"Minor".
Ternary operators are best for simple decisions. For more complex logic, use a regular if statement.
Null Coalescing Operator
The null coalescing operator, written as ??, provides a default value when something is missing or null.
<?php $name = $_GET["name"] ?? "Guest"; echo "Hello, " . $name; ?>
If the URL contains ?name=Travis, the output would be:
Hello, Travis
If no name is provided, the output would be:
Hello, Guest
Common Mistakes
Using One Equals Sign Instead of Two or Three
A single equals sign assigns a value. It does not compare values.
<?php
$isAdmin = false;
if ($isAdmin = true) {
echo "Admin access granted.";
}
?>
This is a mistake because $isAdmin = true assigns true to the variable.
The condition then becomes true.
Use === when comparing values:
<?php
$isAdmin = false;
if ($isAdmin === true) {
echo "Admin access granted.";
} else {
echo "Access denied.";
}
?>
Expected output:
Access denied.
Forgetting Curly Braces
PHP allows some conditionals without curly braces, but using braces makes your code clearer and helps prevent mistakes.
<?php
$loggedIn = true;
if ($loggedIn) {
echo "Welcome!";
}
?>
Making Conditions Too Complicated
Long conditions can be hard to read. You can make them easier to understand by storing part of the condition in a variable.
<?php
$age = 25;
$hasTicket = true;
$isBanned = false;
$canEnter = $age >= 18 && $hasTicket === true && $isBanned === false;
if ($canEnter) {
echo "You may enter.";
} else {
echo "You may not enter.";
}
?>
Expected output:
You may enter.
Real-World Example: Simple Login Check
Here is a simple example of how conditionals might be used to check a username and password.
<?php
$username = "admin";
$password = "secret123";
if ($username === "admin" && $password === "secret123") {
echo "Login successful.";
} else {
echo "Invalid username or password.";
}
?>
Expected output:
Login successful.
This is only a basic learning example. Real login systems should use hashed passwords, sessions, validation, and database-backed user accounts.
Real-World Example: Displaying Different Messages
You can use conditionals to display different messages based on a user's account status.
<?php
$accountStatus = "past_due";
if ($accountStatus === "active") {
echo "Your account is active.";
} elseif ($accountStatus === "past_due") {
echo "Your account has a past-due balance.";
} elseif ($accountStatus === "suspended") {
echo "Your account is suspended.";
} else {
echo "Unknown account status.";
}
?>
Expected output:
Your account has a past-due balance.
Practice Exercises
Try writing your own conditionals using the examples on this page.
- Create a variable called
$temperature. If it is above80, display"It is hot outside.". - Create a variable called
$balance. If it is less than0, display"Your account is overdrawn.". - Create a variable called
$role. Display a different message foradmin,editor, anduser. - Create a variable called
$score. Display a letter grade based on the score. - Use a
switchstatement to display a message based on an order status.
Summary
Conditionals allow PHP programs to make decisions. The most common conditional tools are:
iffor checking a conditionelsefor a fallback optionelseiffor checking additional conditionsswitchfor comparing one value against multiple casesmatchfor a stricter, modern alternative toswitch?:for short simple conditionals??for default values when something is missing or null
As you write more PHP, you will use conditionals constantly. They are used for forms, login systems, permissions, shopping carts, dashboards, error messages, database results, and almost every interactive feature on a website.