基本检查数组元素是否存在:
$foo = isset($country_data['country']) ? $country_data['country'] : '';
这感觉真的很冗长,我现在问是否有更短的方法来做到这一点?
我可以使用@
抑制错误:
$foo = @$country_data['country']
但这似乎是错误的......
我知道使用变量你可以做这样的事情:
$foo = $bar ?: '';
但这不适用于 isset()
。
最佳答案
在 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'] ?? '';
如果每个项目都为 null (!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'], '');
关于php - PHP 中检查数组值是否存在的简短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101693/