PHP:当元素可能不存在时测试数组元素的值
假设我有一个数组 $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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果密钥不存在,它将抛出错误(或警告)。
因此,为了实现这一点,您必须检查它是否确实存在。
有两种方法可以做到这一点:
您可以使用
isset()
(如果
$arr['music'] == null
则为 false):或者使用
array_key_exists()
: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
):Or use
array_key_exists()
:我认为 array_key_exists() 满足您的需求。
I think array_key_exists() meets your needs.
还有另一种解决方案。有些人不喜欢它,因为它使用“@”符号,但我发现它非常可读,所以我使用它。
就这样。对我来说,这是最好的可读解决方案。
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.
That's all. For me, the best readable solution.