user_has_role()

Public

Checks whether a user has a given role.

</> CopyGet raw version
php
  1. /**
  2.  * Determine whether a user has a particular role.
  3.  * Accepts both the role's ID or name.
  4.  * If no user is specified we use the current user.
  5.  *
  6.  * @param integer|string The role's ID or name.
  7.  * @param integer The user's ID.
  8.  * @return boolean Whether the user has the role.
  9.  */
  10. function user_has_role($rid, $uid = NULL) {
  11. $user = user_uid_optional_load($uid);
  12.  
  13. // Make sure we have a valid user object.
  14. if (is_object($user) && isset($user->roles) && is_array($user->roles)) {
  15. return (is_numeric($rid))
  16. ? array_key_exists($rid, $user->roles)
  17. : in_array($rid, $user->roles);
  18. }
  19.  
  20. return FALSE;
  21. }

Comments

Dmitry Drozdik's picture

The better way to use next solution:

  1. function user_has_role($rid, $uid = NULL) {
  2. $user = user_uid_optional_load($uid);
  3. // Make sure we have a valid user object.
  4. if (is_object($user) && isset($user->roles) && is_array($user->roles)) {
  5. return key_exists($rid, $user->roles);
  6. }
  7. return FALSE;
  8. }
alexweber's picture

How is that better? key_exists() isn't even an SPL or Drupal core function and this way you don't allow a numeric rid to be passed as a param.

That said, I just realized that in_array($rid, array_keys($user->roles)) should definitely be replaced with array_key_exists($rid, $user->roles) so thanks for that!