I'm very new to Drupal, so please bear with me if this is a dumb question. According to the globals API, the global $user object returns roles as an array:

[roles] => Array(
  [rid] => name

If I reference $user->roles, it gives me the role names.

Short of looping through like this:

foreach($user->roles as $key => $value){
    error_log("key: " . $key . " ; value: " . $value);

Is there any way to return the role ID (rid) instead of the role name? I need to do conditional processing based on roles, but some of our roles are company-specific, and contain special characters. It would be much easier to work with the ID instead.

2 Answers 2


You can use array_key_exists() to do this:

$rid = 42;

if (array_key_exists($rid, $user->roles)) {
  // Do stuff

If you just want an array of RIDs, you can use array_keys():

$rids = array_keys($user->roles);
$rid = 42;
if(isset($user->roles[$rid])) {
  // Do stuff

is what I usually use. Same basic principle, even more basic coding.


as Mark Trapp cites is really useful for hunting through the keys of the many huge arrays that Drupal produces - e.g., the $fields variable in views templates - dumping the whole thing creates a mess, with just the keys you can usually figure out which element it is you need, and then just dump that.

For dumping variables, be sure to check out Drupal for Firebug - makes huge, unwieldy dumps nicely & elegantly separated from your HTML.

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.