The Null Coalescing Operator and the Ternary Operator are two powerful tools in PHP that enable developers to write concise and expressive code. When used in combination, they provide even more flexibility and allow you to handle conditional assignments effectively. In this article, we'll explore how to combine these operators to write cleaner and more efficient code.

Understanding the Operators

Before diving into their combination, let's briefly explain what each operator does:

  1. Null Coalescing Operator (??): This operator is used to provide a default value when a variable is null. It returns the first non-null value from a list of expressions. Its syntax is: $a ?? $b, which returns $a if it's not null, otherwise it returns $b.
  2. Ternary Operator (?:): The ternary operator is a shorthand way of writing if-else statements. It has the following syntax: $condition ? $valueIfTrue : $valueIfFalse. It evaluates the condition, and if it's true, it returns the first value; otherwise, it returns the second.

Combining Null Coalescing and Ternary Operators

Combining these two operators can be incredibly useful in scenarios where you need to perform conditional assignments. Here's how you can do it:

$result = $condition ? $valueIfTrue : $fallbackValue ?? $defaultValue;

In this structure:

  • $condition is the expression you want to evaluate.
  • $valueIfTrue is the value to be assigned if the condition is true.
  • $fallbackValue is the value you want to use as a fallback if $valueIfTrue is null.
  • $defaultValue is the ultimate fallback value to use if both $valueIfTrue and $fallbackValue are null.

Let's look at some practical examples to illustrate the power of combining these operators.

Example 1: Handling User Preferences

Suppose you have a user profile with customizable settings, and you want to display a default theme if the user hasn't chosen one:

    // Using Null Coalescing Operator and Ternary Operator to handle user preferences
	$selectedTheme = $userTheme ?? ($userTheme !== null ? $userTheme : $defaultTheme);

In this case, if the $userTheme is not set or is null, it falls back to $defaultTheme.

Example 2: Working with API Responses

When dealing with API responses, you may want to ensure that a critical piece of data is present:

    $username = $apiResponse['data']['username'] ?? (isset($apiResponse['data']['username']) ? $apiResponse['data']['username'] : 'default_username');

This line checks if the 'user' key exists in the $apiResponse. If it's missing or null, it halts the script with an error message.