php空位合并,PHP中C#的空合并运算符(??)

从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);

这将尝试每个变量,直到找到满足null的变量为止:

null

null

null

null

如果不存在4,则默认为null。

注意:有一个使用引用的更简单的实现,但是它的副作用是将被测试的项目设置为null(如果尚不存在)。 当数组的大小或真实性很重要时,这可能会产生问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值