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.

/**
 * 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.

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

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

Leave a Reply

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