An identical operator doesn't exist as of PHP 5.6, but you can make a function that behaves similarly.
function first()
{
$count = func_num_args();
for ($i = 0; $i < $count - 1; $i++)
{
$arg = func_get_arg($i);
if (!isset($arg))
{
continue;
}
if (is_array($arg))
{
$key = func_get_arg($i + 1);
if (is_null($key) || is_string($key) || is_int($key) || is_float($key) || is_bool($key))
{
if (isset($arg[$key]))
{
return $arg[$key];
}
$i++;
continue;
}
}
return $arg;
}
if ($i < $count)
{
return func_get_arg($i);
}
return null;
}
Usage:
$option = first($option_override, $_REQUEST, 'option', $_SESSION, 'option', false);
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.
?:
is very close to??
. In fact,?:
actually catches more null-like cases than??
;??
is specifically fornull
and!Nullabe<T>.HasValue
. You sound like you're looking for something more like JavaScript's||
operator. It's like?:
, but JavaScript doesn't complain about referencing undefined keys/members--though it does throw an error if you try to reference a key/member of undefined/null, so you can only go one level. – Zenexersomeres
then changed it totest
? – Pacerierecho @$_REQUEST['someres'] ?: 'hi';
which suppresses the error. – El Yobo