Samuel Bolduc
Samuel Bolduc

Reputation: 19193

Better way of doing isset($variable) and check variable value

I was wondering if there's a better way than what I always do to check the value of a variable that might not be set? For example :

if(isset($_SESSION['super_user']) && $_SESSION['super_user'] == true) {
  echo 'hi super user';
}

It would much simpler to just do this :

if($_SESSION['super_user']) {
  echo 'hi super user';
}

But I would end up with a notice of undefined index. Is there another way of doing such kind of simple validation or I must stick with my actual way of doing it?

Thanks

Upvotes: 0

Views: 86

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157980

For the particular example your current code could be shortened to

if(!empty($_SESSION['super_user']))

however, the right way would be

if ($_SESSION['role'] == 'super_user')

I was wondering if there's a better way than what I always do to check the value of a variable that might not be set?

Yes. Always define all your variables. Like one I posted above. Always have a role element for all your users and there will be no need to check if it ever exists.

Upvotes: 0

insertusernamehere
insertusernamehere

Reputation: 23600

You could initially set $_SESSION['super_user'] to false and only set it to true if the user is a super user. Then you can always use if ($_SESSION['super_user']) {}.

Upvotes: 0

Waleed Khan
Waleed Khan

Reputation: 11467

if (!empty($_SESSION['super_user'])) {
    // ...
}

Upvotes: 1

Related Questions