In the following associative array
$array = array(
[0] => 0
[1] => 1
[2] =>
[3] => 2
[4] =>
)
how can you determine if a given key has an empty (or null) value? I used
if(empty($array[$value]))
and
if(isset($array[$value])) && $array[$value] !=='')
When using empty
I also get false
for the first array value which is zero and isset
doesn't seem to do the trick.
The array can be checked if it is empty by using the array. length property. By checking if the property exists, it can make sure that it is an array, and by checking if the length returned is greater than 0, it can be made sure that the array is not empty.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
You can use the PHP array_values() function to get all the values of an associative array.
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";
}
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.
PHP empty return values states:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
From your array example I take it as you want to exclude the 0 as an integer. If that's the case this would do the trick:
<?php
$array = array(0, 1, '', 2, '');
foreach ($array as $value) {
echo (empty($value) && 0 !== $value) ? "true\n" : "false\n";
}
If you want to exclude other conditions that empty
considers just negate them in that condition. Take in account that this might not be the optimal solution if you want to check other values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With