简体   繁体   中英

How to check an associative array for all null values in php?

This is probably a very trivial question, but please bear with me.

I am trying to read a lot of data into an array of associative arrays. The data contains a lot of empty arrays and arrays with keys set and but all null values. I want to ignore those and only push arrays with at least one key mapped to a non-null value. (The data comes from an excel sheet and it has lots of empty cells that are registered as "set" anyway.) So far I have tried:

if(!empty(${$small_dummy}))
array_push(${$big_dummy}, ${$small_dummy});

That gets rid of the empty arrays but not the ones where all keys map to null. Is there a better way to do this than looping through the entire array and popping all null values?

Judging by the code you have already, you can change:

if(!empty(${$small_dummy}))

to:

if(!empty(array_filter(${$small_dummy})))

That will filter out all empty values (values evaluating to FALSE to be precise) and check if the resulting array is empty. Also see the manual on array_filter() .

Note that this would also filter 0 values so you might need to write a custom callback function for array_filter() .

This isn't an ideal approach, but array_sum will return 0 if all values can't be cast to a numeric value. So :

$small_dummy = array("a" => null, "foo", "", 0); 

if(array_sum($small_dummy) === 0) 

would pass. But this is only the way to go if you are expecting the values to be numeric.

Actually, if the problem is that the array keys have values and therefor are not passing as empty() , the go with array_values :

if(!empty(array_values(${$small_dummy})))

您可以尝试if(!array_filter($ array)){also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM