Checking if a Drupal User has a Role

UPDATE: Over five years later, this post is still one of the most highly trafficked on my blog. Since then I've learned a lot and shared many other tips and modules. This past year I was honored to be a contributor to The Definitive Guide to Drupal 7, which includes many other great tips like this. I highly recommend it if you want to get the latest and greatest information on developing for Drupal.

I'm a little curious why a simple function to check if a user has a role doesn't exist in Drupal yet. Such curiosity that makes me wonder if I've just managed to miss it as long as I've been working with Drupal, so someone feel free to enlighten me. If anyone is looking for the same, please read on...

A fairly common task for me when adding PHP to CCK fields, Views arguments, content templates, etc. is to check whether the current user has been assigned a certain role. Generally in module development you're dealing with permissions and use user_access(), but when you're just customizing a site you often need such role based logic. (Drupal core has some, like the access settings for blocks.)

Use the following simple snippet to check if a user (in this example, it's the logged in user since I'm getting the global $user) has been assigned a certain role on your site:

<?php
 
global $user;

 
// Check to see if $user has the administrator role.
 
if (in_array('administrator', array_values($user->roles))) {
   
// Do something.
 
}
?>

Replace 'administrator' with whatever role it is you're trying to check against. Alternatively, if you keep a helper module for use on your projects, go ahead and drop this function in it:

<?php
/**
 * Check to see if a user has been assigned a certain role.
 *
 * @param $role
 *   The name of the role you're trying to find.
 * @param $user
 *   The user object for the user you're checking; defaults to the current user.
 * @return
 *   TRUE if the user object has the role, FALSE if it does not.
 */
function user_has_role($role, $user = NULL) {
  if (
$user == NULL) {
    global
$user;
  }

  if (
is_array($user->roles) && in_array($role, array_values($user->roles))) {
    return
TRUE;
  }

  return
FALSE;
}
?>

Please let me know if I put a typo up here or you know of an existing or easier way to do this!