简体   繁体   中英

How to check whether an array of array have a key value pair in its values in PHP or Laravel

I have the following array. I want to know whether any of the values of the array contains the key-value pair "RoleCode" => "Admin" .

[
  0 => [
    "RoleCode" => "Admin"
    "RoleName" => "Administrator"
  ]
  1 => [
    "RoleCode" => "PM"
    "RoleName" => "ProjectManager"
  ]
  2 => [
    "RoleCode" => "ScheduleUser"
    "RoleName" => "Schedule User"
  ]
]

I can write a long code to find it out like the following:

$isAdmin = false;
foreach ($user['Roles'] as $role) {
    if ($role['RoleCode'] == 'Admin') {
        $isAdmin = true;
    }
}

Is there any way to do this in a better way?

You could use array_column() and in_array() :

$isAdmin = in_array('Admin', array_column($user['Roles'], 'RoleCode')) ;
  • array_column() will return an array with all values from 'RoleCode' key
  • in_array() will check if Admin is inside

It depends what is better way.

Current solution with adding break when item found:

$isAdmin = false;
foreach ($user['Roles'] as $role) {
    if ($role['RoleCode'] == 'Admin') {
        $isAdmin = true;
        break;
    }
}

will be O(n) in worst case.

Other solutions, like one in another answer

$isAdmin = in_array('Admin', array_column($user['Roles'], 'RoleCode'));

This will be O(n) + O(1) in best case and O(n) + O(n) in worst. More than initial foreach .

Another one is filtering:

$isAdmin = !empty(array_filter(
    $user['Roles'], 
    function ($v) { return $v['RoleCode'] == 'Admin'; }
));

It is always O(n)

So, from the point of readability and performance, initial code is the winner.

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