Drupal 8: Get an Array of User Roles

Published
Updated
Typical Read
1 minutes
Sponsored
Sponsor my site by donating to help support open-source projects, like WordPress Zero Spam, Referrer Analytics & others.
Find your next web developer job
jobs by Indeed

Drupal 8: Get an Array of User Roles was originally published on Nov 19, 2015 and has recently been updated on Aug 6, 2020 to reflect emerging trends.

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.

Did you find Drupal 8: Get an Array of User Roles useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Latest Job Postings
Posted on Aug 9, 2020 at 9:17pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 9:15pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 1:19am
Littleton, CO
jobs by Indeed
Sponsored
Sponsor my site by donating to help support open-source projects, like WordPress Zero Spam, Referrer Analytics & others.
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.
Sponsored
Do you have a great article to share you want to contribute? Contact me about your idea.
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.
Sponsored
Do you run a development agency, freelance developer or offer website services. Contact me today for information about advertising.

1 Comment on “Drupal 8: Get an Array of User Roles”

alkrn

# Apr 14, 2016

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 *

All comments posted on 'Drupal 8: Get an Array of User Roles' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

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.