E-TERN-ization and COALE-scence

We’ve already discussed the ternary operator in another article. However, we haven’t yet covered the null coalescing operator (??). And, because they are somewhat similar (but not identical), we’ll compare and analyze them in this article.

Ternary Operator (?:)

The ternary operator is a shorthand for if ... else and is used when we want to choose between two values based on a condition.

The standard form is: (condition) ? statement1 : statement2;. So, if the condition is true, statement1 will be returned; if it is false, statement2 will be returned.

Example:

  • Checks if $afis == 1
  • If true → returns $user_id
  • If false → returns NULL

Null Coalescing Operator (??)

The null coalescing operator is a shorthand for the following structure:

The standard form is: $variable = $value1 ?? $default_value;. So, if $value1 is set (exists) and is not null, it returns $value1; otherwise, it returns $default_value.

Example:

  • Checks if $_SESSION['request'] exists and is not null
  • If true$data = $_SESSION['request']
  • If false$data = []

Graphic Example

Diagrams with examples

Representation of the two examples from the diagrams:

ChatGPT-Style Summary

Using ChatGPT for a quick synthesis, we can outline the differences as follows:

Characteristic Ternary (?:) Null Coalescing (??)
Purpose Choose between two values based on a condition Choose the first non-null/existing value
Checks Any logical condition (boolean expression) Only if isset() and not null (!= null)
Example $x > 5 ? 'big' : 'small'; $x ?? 'default';
Long equivalent if (...) { ... } else { ... } if (isset(...)) { ... } else { ... }
Number of values checked Two (true/false) Can be a chain ($a ?? $b ?? $c)
Possible outcomes Two possible values First non-null value in the chain
Typical use case Choose based on a condition Provide a default if value is null
  • If we have a logical condition and two possible outcomes → use the ternary operator.
  • If we want to check whether a variable exists and is not null, otherwise provide a default value → use ??.

Mnemonic trick:

  • Ternary = “T” from Test → tests a condition.
  • ?? = “Two question marks” → asks if the variable exists and is not null.

Example for Differentiation

Output:

So:

  • The ternary operator decides based on a logical condition (true/false).
  • ?? gives a default value if the first one does not exist or is null.
  • We can also use ?? in a string: $a ?? $b ?? $c.

Author: Ovidiu.S

I am quite passionate about this professional area as if I know something - no matter how little - I want to share it with others.

Leave a Reply

Your email address will not be published. Required fields are marked *