Reputation: 19193
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
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
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