What's The Difference Between PHP's Elvis (?:) And Null Coalescing (??) Operators?

Published October 27, 2024

Problem: Confusion Between PHP Operators

PHP has two operators that look similar: the Elvis operator (?:) and the null coalescing operator (??). These operators can be mixed up because they look alike and do related things. Knowing how they differ is key for using them correctly in PHP code.

Breaking Down PHP's Conditional Operators

The Elvis Operator (?:)

The Elvis operator (?:) in PHP is a short version of the ternary operator. It returns the first argument if it's "truthy," otherwise it returns the second argument.

The syntax for the Elvis operator is:

$result = $var ?: 'default';

This is the same as:

$result = $var ? $var : 'default';

The Elvis operator uses PHP's loose comparison rules. Any value that's not false in a boolean context is treated as true.

Example: Using the Elvis Operator with Different Types

$number = 0;
$string = '';
$array = [];

echo $number ?: 'Number is falsy'; // Output: Number is falsy
echo $string ?: 'String is falsy'; // Output: String is falsy
echo $array ?: 'Array is falsy';   // Output: Array is falsy
echo true ?: 'True is truthy';     // Output: 1 (true)
echo 'Hello' ?: 'Non-empty string is truthy'; // Output: Hello

The Null Coalescing Operator (??)

The null coalescing operator (??) was added in PHP 7.0. It returns the first argument if it's set and not null. If the first argument is null or not set, it returns the second argument.

The syntax for the null coalescing operator is:

$result = $var ?? 'default';

This is the same as:

$result = isset($var) ? $var : 'default';

The null coalescing operator is useful for handling null values and undefined variables without triggering notices.

Key Differences Between Elvis and Null Coalescing Operators

  1. Behavior with null values:

    • Elvis operator: Treats null as falsy and returns the second argument.
    • Null coalescing operator: Returns the second argument when the first is null.
  2. Handling of undefined variables:

    • Elvis operator: Triggers an E_NOTICE for undefined variables.
    • Null coalescing operator: Handles undefined variables silently, returning the second argument.
  3. Treatment of falsy values:

    • Elvis operator: Returns the second argument for falsy values (0, empty string, false).
    • Null coalescing operator: Returns the first argument if it's set, even if it's falsy.

These differences make each operator useful for specific scenarios in PHP programming.

Tip: Chaining Null Coalescing Operators

You can chain multiple null coalescing operators to check multiple variables in order:

$result = $var1 ?? $var2 ?? $var3 ?? 'default';

This will return the first non-null value among $var1, $var2, and $var3, or 'default' if all are null or undefined.

Practical Examples: When to Use Each Operator

Scenarios Best Suited for the Elvis Operator

The Elvis operator is useful when working with boolean values and checking for non-empty strings or arrays. Here are some examples:

  1. Working with boolean values:
$isAdmin = false;
$message = $isAdmin ?: 'You do not have admin access';
echo $message; // Output: You do not have admin access

$isLoggedIn = true;
$welcomeMessage = $isLoggedIn ?: 'Please log in';
echo $welcomeMessage; // Output: 1 (true)
  1. Checking for non-empty strings or arrays:
$username = '';
$displayName = $username ?: 'Guest';
echo $displayName; // Output: Guest

$items = [];
$itemCount = count($items) ?: 'No items found';
echo $itemCount; // Output: No items found

Tip: Use Elvis for Default Values

The Elvis operator is helpful when setting default values for variables that might be empty or false. For example, when working with form inputs:

$userComment = $_POST['comment'] ?: 'No comment provided';

This ensures that even if the user submits an empty comment, you have a default value to work with.

Scenarios Best Suited for the Null Coalescing Operator

The null coalescing operator is useful for dealing with undefined variables and handling null values in arrays or objects. Here are some examples:

  1. Dealing with undefined variables:
$userInput = $_GET['name'] ?? 'Anonymous';
echo "Hello, $userInput"; // Output: Hello, Anonymous (if 'name' is not set in $_GET)

$config = json_decode(file_get_contents('config.json'), true);
$debugMode = $config['debug'] ?? false;
  1. Handling null values in arrays or objects:
$user = [
    'name' => 'John',
    'email' => null
];

$emailAddress = $user['email'] ?? 'No email provided';
echo $emailAddress; // Output: No email provided

$product = new stdClass();
$product->price = null;

$displayPrice = $product->price ?? 'Price not set';
echo $displayPrice; // Output: Price not set

These examples show how you can use each operator in different scenarios to handle various types of data and conditions in PHP code.