Reputation: 43
I need to check if the fields in an array are empty. I would like to know if there is any function in PHP that does this. I've tried empty()
, but since it checks if the array is empty, it returns false because the array has fields.
The following array is below:
"wm" => array:7 [▼
"make" => null
"model" => null
"version" => null
"portal_plan_id" => null
"portal_highlight_id" => null
"price_type_id" => null
"announce" => null
]
See that the values are null
and they are the ones I need to check.
Thank you!
Upvotes: 3
Views: 1259
Reputation: 21
$array = [
'make' => KIA,
'model' => Koup,
'version' => 5.0,
'portal_plan_id' => null
];
if(in_array(null, $array)){
// do something
}
The above checks if there there is at least one null value, in this case it will evaluate to true
$array = [
'make' => null,
'model' => null,
'version' => null,
'portal_plan_id' => null
];
if(count(array_unique($array)) == 1 && array_unique($array)['make'] == null)
{
//do something
}
Where ['make'] is your first index, you can pick any index. The above will evaluate to true. This is how it works; it checks if all values are the same(array_unique($array)) == 1) and if the first value is null (array_unique($array)['make'] == null). By logic if the first value is null and all values are the same, you can conclude that all values are null
Upvotes: 0
Reputation: 1446
There are two ways to do this depending on what you need. If you want to know if any values are null: http://php.net/manual/en/function.array-search.php
array_search(null, $array)
The array_search will return false if no keys are null. So you can do
if(array_search(null, $array) !== false){
// There is at least one null value
}
If you want to know which keys hold a null value: http://php.net/manual/en/function.array-keys.php
array_keys($array, null)
The array_keys will provide all keys that have a null value. So you can check
if(count(array_keys($array, null)) > 0){
// There is at least one null value. array_keys($array, null) can retrieve the keys that are null
}
Upvotes: 4