Check user for given roles

Drupal 9+

Starting with Drupal 9 we have a dedicated method:

$user->hasRole('my_role_id')

Drupal 8+

To check for a list of given roles:

/**
 * Checks if user has any of given roles.
 *
 * @param array $roles
 *   The role to check.
 *
 * @param AccountInterface $account
 *   User object.
 *
 * @return bool
 *   Whether the account has any of given roles.
 */
function userHasRoles(array $roles, AccountInterface $account): bool {
  return !empty(array_intersect(array_keys($roles), $account->getRoles() ?? [
}


Bellow an example to check specifically for administration role:

/**
 * Check if user has administration role.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
 *   User object.
 *
 * @return bool
 */
function userIsAdministrator(AccountInterface $account): bool {
  $roles = \Drupal::entityTypeManager()
    ->getStorage('user_role')
    ->loadByProperties(['is_admin' => TRUE]);
  return !empty(array_intersect(array_keys($roles), $account->getRoles() ?? []));
}

Drupal 7

You may consider using the new API function added in Drupal 7.36

user_has_role()

This is a wrapper function:

/**
 * Check current/given user for given roles.
 */
function role_access($roles, $account = NULL) {
  if (!is_array($roles) || empty($roles)) {
    return FALSE;
  }

  if (!$account) {
    $account = $GLOBALS ['user'];
  }

  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
}

 

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************