PHP:当元素可能不存在时测试数组元素的值

发布于 2024-11-08 02:02:09 字数 431 浏览 3 评论 0原文

假设我有一个数组 $arr。它可能有一个元素的键名为“music”($arr['music']),我想测试该值是否等于“classical”:

if($arr['music'] === 'classical'){
    //do something cool
}

但是,$ arr 没有包含“music”键的值。为了避免 PHP 错误,我因此执行以下操作:

if($arr['music']){
    if($arr['music'] === 'classical'){
        //do something cool
    }
}

这看起来完全荒谬。在我看来,如果 $arr['music'] 不存在,那么它绝对不等于“古典”。有没有办法避免在测试键的值之前首先测试键是否存在?

Assume I have an array $arr. It's possible that it has an element with a key named 'music' ($arr['music']), and I want to test whether that value equals "classical":

if($arr['music'] === 'classical'){
    //do something cool
}

However, it's possible that $arr does not have a value with the key 'music'. In order to avoid a PHP error, I therefore do the following:

if($arr['music']){
    if($arr['music'] === 'classical'){
        //do something cool
    }
}

This seems totally ridiculous. In MY opinion, if $arr['music'] doesn't exist, then it DEFINITELY doesn't equal 'classical'. Is there a way to avoid first testing whether a key exists before testing it's value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

通知家属抬走 2024-11-15 02:02:09

如果密钥不存在,它将抛出错误(或警告)。
因此,为了实现这一点,您必须检查它是否确实存在。
有两种方法可以做到这一点:

您可以使用 isset()(如果 $arr['music'] == null 则为 false):

if(isset($arr['music']) && $arr['music'] === 'classical'){ 
    //do something cool
}

或者使用 array_key_exists()

if(array_key_exists('music', $arr) && $arr['music'] === 'classical'){
    //do something cool
}

If the key does not exist it will throw an error (or a warning).
So in order for that to happen, you have to check if it does exist.
Here are two ways to do that:

You can check it using isset() (which will be false if $arr['music'] == null):

if(isset($arr['music']) && $arr['music'] === 'classical'){ 
    //do something cool
}

Or use array_key_exists():

if(array_key_exists('music', $arr) && $arr['music'] === 'classical'){
    //do something cool
}
活雷疯 2024-11-15 02:02:09

我认为 array_key_exists() 满足您的需求。

I think array_key_exists() meets your needs.

煮茶煮酒煮时光 2024-11-15 02:02:09

还有另一种解决方案。有些人不喜欢它,因为它使用“@”符号,但我发现它非常可读,所以我使用它。

if (@$arr['music'] === 'classical') ...

就这样。对我来说,这是最好的可读解决方案。

There is another solution. Some people doesn't like it because it uses the '@' sign, but I find it very readable so I use it.

if (@$arr['music'] === 'classical') ...

That's all. For me, the best readable solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文