Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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

array_keys($someArray)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top