Home > other >  how to use array_search to look for NULL instead of a value
how to use array_search to look for NULL instead of a value

Time:11-04

I get from a query a list of records where some of them or all can have NULL values. Sample data:

ID All Name Surname
22 4 John Smith
34 4 Mike Reed
NULL 4 NULL NULL
NULL 4 NULL NULL

So in this case the array will contain 4 elements and the third one is the first with NULL value for ID. So I am looking for a way in PHP to determine the first NULL Id (so this will return 3). Edge cases are with all NULL (should return 1) or no NULL (should return 0)

I was looking for array_search but what I don't get is how to search for NULL instead of a value...

CodePudding user response:

Wilmanicesir's answer will be more flexible if you need more comparison options, but another way using array_search would be like this:

$nullIdIndex = array_search(null, array_column($data, 'ID'));

Though, note PHP arrays are zero-indexed, so in your sample data this will return 2 not 3, if all are null it will be 0 because that's the first null instance, and if none are null it will return false.

Also, per the comment in the PHP docs explaining this, be careful that this will return the actual position in the array where the null is found; if your data has associated custom keys, they will not be the value returned by array_search using this method.

CodePudding user response:

Assuming that you only have to check on ID this could be a solution:

# Filter out persons with an id
$noIds = array_filter($data,
    function ($person) {
        return $person['id'] === NULL;
    }
);

// The first result is also the first find
$firstHit = $noIds[0]
  •  Tags:  
  • php
  • Related