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.


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);
  • Thanks! For some reason, it never occurred to me to go with straight php - I was thinking there was some Drupal function I was supposed to use. – EmmyS Apr 18 '11 at 19:54
  • @EmmyS there's user_roles(), but it just provides an array that's structured in the same way as $user->roles. Any other possible Drupal API function would just be a needless extra DB call. – user7 Apr 18 '11 at 19:56
$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, privacy policy and cookie policy

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