1

I want to print in a page--node--17.tpl.php a code to check for roles from the logged in user and then determine what should be shown, so basically a user must have BOTH roles A and C and if they do i print xxx If they have roles A and B i write yyy if they have roles B and C i print zzz

So the code below can check for one role, but how do i do both.. its important that BOTH roles need to be there, a user with just one of the roles will not qualify.

thank u

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

also i have this code but i think this is only checking one of the roles, so it checks for either A or B

<?php
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
    if (empty($check) ? FALSE : TRUE) {
    // is admin
    } else {
    // is not admin
    }
?>
1
  • I have to say, just seeing "Checking if user has role", and separately, "in tpl file" makes me draw a sharp breath. Both of these indicate that something is quite wrong with what you are doing. You should strongly consider a different approach.
    – Letharion
    Nov 15, 2013 at 22:18

2 Answers 2

2

It would be simple as:

global $user;

if (in_array('administrator', array_values($user->roles)) &&  in_array('moderator', array_values($user->roles))) {
    // is admin
} else {
    // is not admin
}
1

array_intersect() returns the intersected array, so your condition will pass if either of the roles are present.

There are different ways to approach it but this is probably the simplest:

$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (count($check) == 2) {
  // ...

On a slightly separate note, there's a bit of redundancy in your code

if (empty($check) ? FALSE : TRUE)

Would be simply

if (empty($check))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.