开发者

PHP: Testing for the value of an array element when there is a chance that element doesn't exist

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 d开发者_如何学JAVAo 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?


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
}


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.

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜