Error message

Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu_set_active_trail() (line 2404 of /mnt/stor1-wc1-dfw1/376356/

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.

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