Skip to content
Advertisement

Check if a given key in an associative array has a value

Assume I have an array like this:

$Data = array(
    'User1' => array(
        'FirstName'  => 'John',
        'MiddleName' => '',
        'LastName'   => 'Doe',
    ),
    'User2' => array(
        'FirstName'  => 'John',
        'MiddleName' => '',
        'LastName'   => 'Smith',
    ),
);

I want to check, if no dataset in the array has a value for MiddleName.
I wanted to ask, if there is a built-in function/one-liner in PHP to do something like this:

IF( AllEmpty($Data["MiddleName"]) ) { Do something }

Thank you very much!

Advertisement

Answer

If you insist on a one-liner, it can be done like this:

if (!array_filter(array_column($Data, 'MiddleName'))) {
    echo 'Nothing here';
}

How it works:

  • array_column obtains all the values of ‘MiddleName’ as an array ['', '']
  • array_filter (without any additional parameters) returns an array with any falsey values removed, resulting in an empty array as empty strings are considered falsey
  • since an empty array is itself falsey, we negate the expression so that the condition can be met (it could be also written as array_filter(array_column($Data, 'MiddleName')) === [] if we want to be explicit or even as empty(array_filter...)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement