
PHP - Conditional Operators
Conditional operators in PHP help make quick decisions in your code without using lengthy if-else
statements. The two main conditional operators are:
-
Ternary Operator (
?:
) – A shorthand forif-else
conditions. -
Null Coalescing Operator (
??
) – Used to check if a value exists before using it.
Let's explore these operators in detail with examples.
1. PHP Ternary Operator (?:
)
The ternary operator (?:
) is a shorthand for a simple if-else
condition.
Syntax:
Example:
Output:
Explanation:
-
If
$age
is18
or more, it prints "You are an adult". -
Otherwise, it prints "You are a minor".
This is equivalent to:
But the ternary operator makes the code shorter and cleaner.
2. PHP Null Coalescing Operator (??
)
The null coalescing operator (??
) checks if a variable exists and is not null
. If the left operand is not null
, it is returned; otherwise, the right operand is returned.
Syntax:
Example:
Output (if user
is not provided in the URL):
Explanation:
-
If
$_GET['user']
is set, its value is assigned to$username
. -
If it is not set (or is
null
),"Guest"
is assigned instead.
This is equivalent to:
But the ??
operator makes it more concise.
Using Ternary and Null Coalescing Together
You can combine both operators for even more efficient code.
Example:
-
If
$_GET['role']
exists, its value is used. -
Otherwise, it defaults to
"guest"
. -
If the role is
"admin"
, it prints "Welcome, Admin!". -
Otherwise, it prints "Access Denied".
Key Takeaways
✅ The ternary operator (?:
) is a shorthand for if-else
.
✅ The null coalescing operator (??
) provides a default value if a variable is null
or not set.
✅ Both operators make PHP code cleaner and more readable.
Conclusion
PHP conditional operators allow you to write shorter and more efficient conditional expressions. The ternary operator helps in quick decision-making, while the null coalescing operator ensures variables have default values when needed.
By mastering these operators, you can reduce the complexity of your code and make it easier to maintain.
Leave a Comment