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?
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():