Reputation: 6173
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?
Upvotes: 1
Views: 1591
Reputation: 54841
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.
Upvotes: 4
Reputation: 19780
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'
keyin_array()
will check if Admin
is insideUpvotes: 5