In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn’t:
echo $count ? $count : 10; // outputs 10
There is also a shorthand for that which allows you to skip the second element if it’s the same as the first one:
echo $count ?: 10; // also outputs 10
In PHP 7 we additionally get the
?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.
// $a is not set $b = 16; echo $a ?? 2; // outputs 2 echo $a ?? $b ?? 7; // outputs 16
This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It’s kind of a small feature but it’s one that I know I’ll be using as soon as my applications upgrade to PHP 7.