检查PHP中是否存在数组值的简短方法

时间:2016-12-12 13:11:25

标签: php

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

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

这感觉真的很冗长,我现在要问的是有更短的方法吗?

我可以使用@

来抑制错误
$foo = @$country_data['country']

但那似乎有点不对......

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

$foo = $bar ?: '';

但这不适用于isset()

1 个答案:

答案 0 :(得分:4)

在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'], '');