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:

  1. Ternary Operator (?:) – A shorthand for if-else conditions.

  2. 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:

(condition) ? (value_if_true) : (value_if_false);

Example:

<?php $age = 18; $result = ($age >= 18) ? "You are an adult" : "You are a minor"; echo $result; ?>

Output:

You are an adult

Explanation:

  • If $age is 18 or more, it prints "You are an adult".

  • Otherwise, it prints "You are a minor".

This is equivalent to:

if ($age >= 18) { echo "You are an adult"; } else { echo "You are a minor"; }

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:

$value = $variable ?? $default_value;

Example:

<?php $username = $_GET['user'] ?? 'Guest'; echo "Hello, $username!"; ?>

Output (if user is not provided in the URL):

Hello, Guest!

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:

if (isset($_GET['user'])) { $username = $_GET['user']; } else { $username = 'Guest'; }

But the ?? operator makes it more concise.


Using Ternary and Null Coalescing Together

You can combine both operators for even more efficient code.

Example:

<?php $role = $_GET['role'] ?? 'guest'; $message = ($role == 'admin') ? "Welcome, Admin!" : "Access Denied"; echo $message; ?>
  • 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.