Checking if a user has a given role in D6

Drupal's API doesn't contain any ready-made function to check if a user has a certain role. While it's certainly easy enough to do, it can take a moment to figure out initially. Here's a little function that demonstrates how to do it. It isn't itself particularly useful since checking for roles is trivial without it, but it should serve as a point of demonstration.

<?php
/**
 * Function to determine is a given user has a role.
 *
 * @param $role
 *  A string containing the role we want to check.
 * @param $uid
 *  The UID of the user we wish to examine for the role. If not provided,
 *  the currently logged in user will be user.
 * @return
 *  TRUE if the user has the role. FALSE otherwise.
 */
function _user_has_role($role, $uid = FALSE) {
  // Can't just check for !$uid since UID 0 is the anonymous user.
  if ($uid === FALSE) {
    global $user;
  }
  else {
    $user = user_load($uid);
  }
  
  // Check for the role.
  if (in_array($role, $user->roles)) {
    // Role found
    return TRUE;
  }
  // Role not found.
  return FALSE;
}
?>
Tags: