Is there a ternary operator or the like in PHP that acts like ??
of C#?
??
in C# is clean and shorter, but in PHP you have to do something like:
// This is absolutely okay except that $_REQUEST['test'] is kind of redundant.
echo isset($_REQUEST['test'])? $_REQUEST['test'] : 'hi';
// This is perfect! Shorter and cleaner, but only in this situation.
echo null? : 'replacement if empty';
// This line gives error when $_REQUEST['test'] is NOT set.
echo $_REQUEST['test']?: 'hi';
PHP 7 adds the null coalesce operator:
You could also look at short way of writing php's ternary operator ?: (php >=5.3 only)
And your comparison to C# is not fair. "in PHP you have to do something like" - In C# you will also have a runtime error if you try to access a non-existent array/dictionary item.
??
is binary in C#, not ternary. And it has no equivalence in PHP prior to PHP 7.Prior to PHP 7, there isn't. If you need to involve
isset
, the pattern to use isisset($var) ? $var : null
. There's no?:
operator that includes the characteristics ofisset
.An identical operator doesn't exist as of PHP 5.6, but you can make a function that behaves similarly.
Usage:
This would try each variable until it finds one that satisfies
isset()
:$option_override
$_REQUEST['option']
$_SESSION['option']
false
If 4 weren't there, it would default to
null
.Note: There's a simpler implementation that uses references, but it has the side effect of setting the tested item to null if it doesn't already exist. This can be problematic when the size or truthiness of an array matters.
I use function. Obviously it is not operator, but seems cleaner than your approach:
Usage:
The Null Coalesce Operator, (
??
) has been accepted and implemented in PHP 7. It differs from the short ternary operator (?:
) in that??
will suppress theE_NOTICE
that would otherwise occur when attempting to access an array where it doesn't have a key. The first example in the RFC gives:Notice that the
??
operator does not require the manual application ofisset
to prevent theE_NOTICE
.