Drupal 8: Get an Array of User Roles

Need an array of user roles in your Drupal 8 site? Say goodbye to user_roles(), say hello to user_role_names(). This function will return an associative array with the role id as the key and the role name as the value. For more information, see https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_role_names/8.2.x.

Need an array of user roles in your Drupal 8 site? Say goodbye to user_roles(), say hello to user_role_names().

This function will return an associative array with the role id as the key and the role name as the value.

/**
 * Retrieves the names of roles matching specified conditions.
 * @link https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_role_names/8
 */
function user_role_names($membersonly = FALSE, $permission = NULL) {
  return array_map(function($item) {
    return $item->label();
  }, user_roles($membersonly, $permission));
}

For more information, see https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_role_names/8.2.x.

Comments

  1. Do you know, how to get user ID(s) by name or role?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All comments are held for moderation and only published when on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

icon-search icon-link