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.


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());
| improve this answer | |
  • 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). – kiamlaluno Nov 14 '12 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;
| improve this answer | |
  • 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. – kiamlaluno Nov 14 '12 at 16:00
  • 4
    $rid = ($role = user_role_load_by_name()) ? $role->rid : NULL; – Pierre Buyle Mar 22 '13 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.

| improve this answer | |
  • 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. – kiamlaluno Mar 15 '16 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. – BlondeSwan Oct 11 '19 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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