Skip to content
PHP Logo

What is the difference between the Null Coalescing Operator and the Ternary Operator in PHP?

The Null Coalescing Operator (??) is used to check if a variable is set and not null, and if it is not, it returns a default value. The Ternary Operator (?:) is a shorthand way of writing an if-else statement in a single line. While both operators can be used for similar purposes, the Null Coalescing Operator is specifically designed for handling null values, while the Ternary Operator can handle any condition.

php
// Null Coalescing Operator example
$variable = $someVariable ?? $defaultValue;

// Ternary Operator example
$variable = isset($someVariable) ? $someVariable : $defaultValue;