简体   繁体   English

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

[英]Pick first non-empty value from a list in PHP

Assuming $a , $b , $c , $d , $e be some random unknown values. 假设$a$b$c$d$e是一些随机未知值。 I'd like to pick one value from them which is not empty with priority in that order. 我想从它们中选择一个值,该值不是空的,具有该顺序的优先级。

To be brief, I want to achieve the same result as in javascript return $a || $b || $c || $d || $e || 0; 简而言之,我希望获得与javascript return $a || $b || $c || $d || $e || 0;相同的结果 return $a || $b || $c || $d || $e || 0; does. 确实。

Currently, in PHP we use (parenthesis are just for readability): 目前,在PHP中我们使用(括号仅用于可读性):

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

Or since PHP 5.3 或者从PHP 5.3开始

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

I can see the 5.3 syntax is lighter and almost similar to that of JavaScript. 我可以看到5.3语法更轻,几乎与JavaScript类似。 But I wonder if there is something more elegant available in PHP. 但我想知道PHP中是否有更优雅的东西。

The other question marked as duplicate to this asks for a solution to do this. 标记为重复的另一个问题要求提供解决方案。 But here I am asking for improvement in case there is something available in PHP natively. 但是在这里我要求改进,以防本地存在PHP的东西。 This is to ensure we use best possible solution for the said problem. 这是为了确保我们为所述问题使用最佳解决方案。

You can use the following function: 您可以使用以下功能:

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

Then call it like that: 然后这样称呼它:

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

My original question is about some native feature that allows easy pick mechanism for a set of variables. 我最初的问题是关于一些本机特性,它允许一组变量的简单选择机制。 I already indicated that the short ternary operator syntax does it. 我已经指出短三元运算符语法可以做到这一点。

However, from the above answers and lot of search around I come to the conclusion that the ternary syntax is the shortest available method in PHP to achieve the said result. 但是,从上面的答案和大量的搜索中我得出结论,三元语法是PHP中用于实现上述结果的最短可用方法。

I was expecting something like pick($a, $b, $c, $d, $e, ....); 我期待像pick($a, $b, $c, $d, $e, ....); , similar to COALESCE(colname, 0) of SQL but sadly no such function exists yet, AFAIK. ,类似于SQL的 COALESCE(colname, 0) ,但遗憾的是还没有这样的函数,AFAIK。


Since people are answering with custom functions for this, I tend to put my version of such custom functions. 由于人们正在为此回答自定义函数,我倾向于使用我的自定义函数版本。

/**
 * 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;
}

You can call above function with any number of arguments , like: 您可以使用任意数量的参数调用上面的函数,例如:

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

Or, if you have an array instead of independent variables: 或者,如果您有一个数组而不是自变量:

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

Or define another function for array arguments if you like. 或者如果你愿意,可以为数组参数定义另一个函数 @gothdo did this pretty well. @gothdo做得很好。 Just add a default value for fallback and its good to go. 只需为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 (count($args) && !($arg = array_shift($args)));

    return isset($arg) ? $arg : $default;
}

I still prefer the ternary syntax, because no other approach will work as good if the variable is not defined at all, and we want to check isset instead of empty or truthy value. 我仍然更喜欢三元语法,因为如果根本没有定义变量,其他任何方法都不会有效,我们要检查isset而不是emptytruthy值。

See the below case. 见下面的案例。 We cannot pass $a , $b etc... to a function unless we are sure it is defined, otherwise it will raise error. 我们不能将$a$b等传递给函数,除非我们确定它已定义,否则会引发错误。

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

Looks dirty, but its consistent and straight forward. 看起来很脏,但它一贯而直截了当。 Plus, native approach is usually better on performance. 此外,原生方法通常在性能上更好。

Well, in PHP 7 , you can use null coalescing operator like: 好吧,在PHP 7中 ,您可以使用null合并运算符,如:

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

This checks isset internally. 这种检查isset内部。 Pretty clean! 很干净! Right? 对?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM