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

时间:2016-04-13 06:45:52

标签: php ternary-operator

假设$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的东西。这是为了确保我们为上述问题使用最佳解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用以下功能:

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

然后这样称呼:

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

答案 1 :(得分:0)

我原来的问题是关于一些原生功能,它允许为一组变量提供简单的选择机制。我已经指出短三元运算符语法就可以了。

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

我期待pick($a, $b, $c, $d, $e, ....);之类的东西,类似于 SQL COALESCE(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 (!($arg = array_shift($args)));

    return $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);

如果您愿意,可以为数组参数定义另一个函数。 @gothdo做得很好。只需为fallback添加一个默认值即可。

/**
 * 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 (!($arg = array_shift($args)));

    return $arg ? $arg : $default;
}

我仍然更喜欢三元语法,因为如果根本没有定义变量,其他任何方法都不会有效,我们想检查isset而不是empty或{{ 1}}值。

见下面的案例。我们无法将truthy$a等传递给函数,除非我们确定它已定义,否则会引发错误。

$b

看起来很脏,但它一贯而且直截了当。另外,原生方法通常在性能上更好。

嗯,在 PHP 7 中,您可以使用null coalescing operator之类的内容:

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

这会在内部检查 $value = $a ?? $b ?? $c ?? 0; 。很干净!正确?

相关问题