0

I have a database calls that is providing me a list of roles that a user has access to on a specific page. There is a piece of logic that I am protecting using this permission data.

I am trying to figure out how to check if the role the user has exists in an array of allowed roles to see that data.

Example code:

$roles = ['User', 'Admin', 'HR'];
$userRoleFromDB = 'Admin';

...
// Check to see if the user has the Admin Role
<?php if (in_array($userRoleFromDB, $roles))){?>
  Secret Stuff Here
<?php } ?>

While the above code works just fine if I am checking that the user has the Admin role, I am trying to figure out how I can check multiple roles against an array.

$roles = ['User', 'Admin', 'HR'];
$userRoleFromDB = ['Admin', 'HR'];

...
// Check to see if the user has the Admin OR HR Role
<?php if (in_array($userRoleFromDB, $roles))){?>
  Secret Stuff Here
<?php } ?>

Is there something similar to in_array that can take two arrays for this check?

SBB
  • 8,560
  • 30
  • 108
  • 223

1 Answers1

3

You could use array_intersect(), then check if the count of matching roles is more than 0.

$matching_roles = array_intersect($roles, $userRoleFromDB);
if(count($matching_roles) > 0) { ?>

    Secret Stuff Here

<?php }

Additionally, using an empty array in an IF statement will return false, and using an array with any values will return TRUE, so you could also just do:

$matching_roles = array_intersect($roles, $userRoleFromDB);
if($matching_roles) { ?>

    Secret Stuff Here

<?php }

Alternatively, you could check it inside of a loop.

foreach($userRoleFromDB as $role) {
    if(in_array($role, $roles)) { ?>

        Secret Stuff Here

        <?php break;
    }
}

Inside the loop, use in_array() to check if the variable is in the array, and use break; to end the loop after your Secret Stuff Here is executed, so it's not executed multiple times.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71