Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of array keys with null values?

Tags:

arrays

php

null

key

I have an array. How can I get a list of the keys that have null values? Is there some short way to find them?

like image 469
JohnK Avatar asked Dec 14 '22 21:12

JohnK


2 Answers

Actually, array_keys has an optional search_value parameter, so you can just put:

array_keys($array, null, true);

You must set the third parameter (strict comparison) to true for it to match only nulls.

like image 161
Don't Panic Avatar answered Dec 17 '22 10:12

Don't Panic


Here's the function that I came up with:

function find_nulls($a) {
    return array_keys(array_filter($a, function($b) {
       return is_null($b);
    }) );
}

It seems to work as desired.

like image 43
JohnK Avatar answered Dec 17 '22 11:12

JohnK