How to check if an associative array has an empty or null value
Looked at all the answers and I don't like them. Isn't this much simpler and better? It's what I am using:
if (in_array(null, $array, true) || in_array('', $array, true)) {
// There are null (or empty) values.
}
Note that setting the third parameter as true means strict comparison, this means 0 will not equal null - however, neither will empty strings ('') - this is why we have two conditions. Unfortunately the first parameter in in_array has to be a string and cannot be an array of values.
use array_key_exists()
and is_null()
for that. It will return TRUE
if the key exists and has a value far from NULL
Difference:
$arr = array('a' => NULL);
var_dump(array_key_exists('a', $arr)); // --> TRUE
var_dump(isset($arr['a'])); // --> FALSE
So you should check:
if(array_key_exists($key, $array) && is_null($array[$key])) {
echo "key exists with a value of NULL";
}