自 PHP 5.6 起不存在相同的运算符,但您可以创建一个行为相似的函数。
/**
* Returns the first entry that passes an isset() test.
*
* Each entry can either be a single value: $value, or an array-key pair:
* $array, $key. If all entries fail isset(), or no entries are passed,
* then first() will return null.
*
* $array must be an array that passes isset() on its own, or it will be
* treated as a standalone $value. $key must be a valid array key, or
* both $array and $key will be treated as standalone $value entries. To
* be considered a valid key, $key must pass:
*
* is_null($key) || is_string($key) || is_int($key) || is_float($key)
* || is_bool($key)
*
* If $value is an array, it must be the last entry, the following entry
* must be a valid array-key pair, or the following entry's $value must
* not be a valid $key. Otherwise, $value and the immediately following
* $value will be treated as an array-key pair's $array and $key,
* respectfully. See above for $key validity tests.
*/
function first(/* [(array $array, $key) | $value]... */)
{
$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;
}
用法:
$option = first($option_override, $_REQUEST, 'option', $_SESSION, 'option', false);
这将尝试每个变量,直到找到满足的变量isset()
:
$option_override
$_REQUEST['option']
$_SESSION['option']
false
如果 4 不存在,它将默认为null
.
注意:有一个使用引用的更简单的实现,但它具有将测试项设置为 null 如果它不存在的副作用。当数组的大小或真实性很重要时,这可能会出现问题。