On log in I want to check a third party data source (table in the db) for a user, and if found I want to add a role to that user.

I don't want to guess the rid of the role, I want to get it from the role name.

3 Answers 3


This is quite straightforward with user_roles() and array_search(). Below is a function which will return the role ID if there is a role matching the name and FALSE otherwise.

function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);

// Sample usage
$rid = get_role_by_name('administrator');

One liner would be:

$rid = array_search('administrator', user_roles());
  • 1
    The query executed by user_roles() is tagged translatable, which means a module could translate the role names. Drupal translates the role names only for the default roles (i.e. anonymous user, and authenticated user).
    – apaderno
    Commented Nov 14, 2012 at 16:11

Knowing the machine name of the role, it is enough to use user_role_load_by_name().

if ($role = user_role_load_by_name('Role Name')) {
  // The role ID is in $role->rid.

If the Role might not exist...

$role = user_role_load_by_name('Role Name');

$role_id = $role ? $role->rid : NULL;
  • 3
    I much prefer this approach, as with the other approach the role names could be translated. In fact, the query executed by user_roles() is tagged translatable. Drupal translates only the names for the default roles, but a module could translate the other role names too.
    – apaderno
    Commented Nov 14, 2012 at 16:00
  • 4
    $rid = ($role = user_role_load_by_name()) ? $role->rid : NULL; Commented Mar 22, 2013 at 14:14

The best way to identify role and its id is from SQL. Run this query in your SQL editor.

select * from roles;

And you will get the list of Roles including the id and weight.

  • 1
    The best way is using the API provided by Drupal. Accessing directly the database, when there is an API, is never a good idea, nor the best way.
    – apaderno
    Commented Mar 15, 2016 at 12:34
  • This is a very easy way to get the roles! I'm not surprised the Drupal Stack Exchange Police voted down such a simple solution.
    – user92800
    Commented Oct 11, 2019 at 20:34
  • If all you want is to know the role id you can go to /admin/people/permissions/roles and the role id will be in the url of the role you select.
    – wranvaud
    Commented Jul 1, 2021 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.