Jump to content

  •  

Photo
- - - - -

P7: Check if a Variable is set

PHP4Beginners

  • Please log in to reply
No replies to this topic

#1 DraxxTV

DraxxTV

    Member

  • SuperGeek
  • PipPip
  • 14 posts

Posted 06 July 2014 - 06:40 PM

When  you are using a large number of variables which are collected a range of different places, from a form for example, It is very useful to find out if a variable is set. In this tutorial I will be teaching you to do just that. To so this, I will be introducing a new datatype, a Boolean. A Boolean is a value defined as true or false.

In this example, I am going to check if a variable called notloggedin is true. If it is then we are going to ask them to log in. If it isn't however, I will be running some code.

<?
if($notloggedin==true){
    echo "You are not logged in... Please log in to see this page.";
}else{
    echo "You are logged in... Run the rest of the code ";
}
?>

As you can see, although the variable has not been set, it is still showing you that the user is logged in. Clearly this isn't what we want so we should see if it has been set yet. If it hasnt then we can set it to a default value. To do this we can do the following:

<?
if(!isset($notloggedin)){
    $notloggedin=false;
}
if($notloggedin==true){
    echo "You are not logged in... Please log in to see this page.";
}else{
    echo "You are logged in... Run the rest of the code ";
}
?>

This way, the code now functions as intended. As you can tell this can be very useful if used correctly.

 







Also tagged with one or more of these keywords: PHP4Beginners