【问题标题】:A short method of checking if array value exists in PHP检查 PHP 中是否存在数组值的简短方法
【发布时间】:2017-04-27 08:50:42
【问题描述】:

基本检查数组元素是否存在:

$foo = isset($country_data['country']) ? $country_data['country'] : '';

感觉真的很冗长,我现在想问有没有更短的方法来做到这一点?

我可以使用@ 抑制错误:

$foo = @$country_data['country']

但这似乎有点不对……

我知道使用变量你可以做这样的事情:

$foo = $bar ?: '';

但这不适用于isset()

【问题讨论】:

    标签: php


    【解决方案1】:

    在 PHP7 中你可以使用null coalescing operator ??

    它将采用链中的第一个非空值。

    你可以这样做:

    $foo = $country_data['country'] ?? '';
    

    这和做的一样

    $foo = isset($country_data['country']) ? $country_data['country'] : '';
    

    而且,您还可以进一步链接。

    例如,您可以尝试使用多个数组索引:

    $foo = $country_data['country'] ?? $country_data['state'] ?? $country_data['city'] ?? '';
    

    如果每一项都是空的(!isset()),它会在最后取空字符串,但如果其中任何一个存在,链就会停在那里。

    如果你没有 PHP7(你应该),你可以使用我在 this answer 找到的这个函数:

    function coalesce() {
      $args = func_get_args();
      foreach ($args as $arg) {
        if (!empty($arg)) {
          return $arg;
        }
      }
      return NULL;
    }
    
    $foo = coalesce($country_data['country'], '');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-16
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2019-11-06
      • 1970-01-01
      相关资源
      最近更新 更多