从PHP中的列表中选择第一个非空值


Pick first non-empty value from a list in PHP

假设$a$b$c$d$e是一些随机未知值。我想从中选择一个值,该值不为空,并按该顺序排列优先级。

简而言之,我希望获得与javascript return $a || $b || $c || $d || $e || 0;中相同的结果。

目前,在PHP中我们使用(括号只是为了可读性):

return $a ? $a : ($b ? $b : ($c ? $c : ($d ? $d : ($e ? $e : 0))));

或者从PHP 5.3 开始

return $a ?: $b ?: $c ?: $d ?: $e ?: 0;

我可以看到5.3的语法更轻,几乎与JavaScript的语法相似。但我想知道PHP中是否还有更优雅的东西。

另一个标记为重复的问题要求解决此问题。但在这里,我要求改进,以防PHP本身有可用的东西。这是为了确保我们对上述问题使用尽可能好的解决方案。

您可以使用以下函数:

function firstNonEmpty(array $list) {
  foreach ($list as $value) {
    if ($value) {
      return $value;
    }
  }
  return null;
}

然后这样称呼它:

$value = firstNonEmpty([0, null, 3, 2]);

我最初的问题是关于本机的一些功能,该功能允许对一组变量进行简单的选择机制。我已经指出,短三元运算符语法可以做到这一点

然而,从上面的答案和周围的大量搜索中,我得出结论,三元语法是PHP中实现上述结果的最短方法。

我期待着类似pick($a, $b, $c, $d, $e, ....);的东西,类似于SQLCOALESCE(colname, 0),但遗憾的是,AFAIK还不存在这样的函数。


由于人们对此使用自定义函数进行回答,所以我倾向于使用我的此类自定义函数版本。

/**
 * Function to pick the first non-empty value from the given arguments
 * If you want a default value in case all of the given variables are empty,  
 * pass an extra parameter as the last value.
 *
 * @return  mixed  The first non-empty value from the arguments passed   
 */
function coalesce()
{
    $args = func_get_args();
    while (count($args) && !($arg = array_shift($args)));
    return isset($arg) ? $arg : null;
}

您可以用任意数量的参数调用上述函数,如:

$value = coalesce($a, $b, $c, $d, $e, 0);

或者,如果你有一个数组而不是自变量:

// Assuming, $array = array($a, $b, $c, $d, $e);
$value = call_user_func_array('coalesce', $array);

如果愿意,也可以为数组参数定义另一个函数@哥特多做得很好。只需为回退添加一个默认值就可以了。

/**
 * Function to pick the first non-empty value from the given array
 * If you want a default value in case all of the values in array are empty,  
 * pass the default value as the second parameter.
 *
 * @param   array  $args     The array containing values to lookup
 * @param   mixed  $default  The default value to return
 *
 * @return  mixed  The first non-empty value from the arguments passed   
 */
function coalesce_array(array $args, $default = null)
{
    while (count($args) && !($arg = array_shift($args)));
    return isset($arg) ? $arg : $default;
}

我仍然更喜欢三元语法,因为如果变量根本没有定义,那么没有其他方法可以很好地工作,并且我们希望检查isset而不是emptytruthy

请参阅以下案例。除非我们确定函数已定义,否则我们不能将$a$b等传递给函数,否则它将引发错误。

$value = isset($a) ? $a : isset($b) ? $b : isset($c) ? $c : 0;

看起来很脏,但它始终如一,直截了当。此外,本机方法通常在性能上更好

好吧,在PHP7中,您可以使用空合并运算符,如:

 $value = $a ?? $b ?? $c ?? 0;

这在内部检查isset。很干净!正确的