简体   繁体   中英

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!

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... )

using loop to check each element

foreach($Data as $x => $value) {
  if(!middlename_check($value['MiddleName'])){
    echo 'MiddleName is empty!';
  }
  // Do something
}

function middlename_check($middlename) {
  if($middlename != '') {
    return true;
  }
  return false;
}

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