Drupal - How do I find the role id from role name?

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;

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());

Tags:

Users

7