Difference between `if (isset ($ _ SESSION)) and` if ($ _SESSION) `?

I noticed that often people just write

<?php if($_SESSION['username']) {...} ?> 

while i used:

  <?php if(isset($_SESSION['username'])) {...} ?> 

Can someone explain the difference when checking if a variable is set (which I will use for it)?

+4
source share
3 answers

According to PHP.net, isset () does the following:

Determine if the variable is set and is not NULL.

When recording:

 <?php if($_SESSION['username']) {...} ?> 

You check to see if $ _SESSION ['username'] matches true. In other words, you are checking to see if the value is greater than false.

According to PHP.net , the following are FALSE:

When converting to boolean, the following values ​​are considered FALSE:

 the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags 

As you can see, unset variables / NULL variables are considered FALSE. Therefore, by checking whether the $ _SESSION element is true, you also determine whether it exists.

Isset, on the other hand, actually checks if a variable exists. If you want to know if there is a SESSION variable with this name, use isset (), since checking it for TRUE / FALSE does not depend on whether or not the variable exists.

Next, consider the following examples:

 $_SESSION['a'] = FALSE; if($_SESSION['a']){ echo 'Hello'; //This line is NOT echo'd. } if(isset($_SESSION['b'])){ echo 'Hello'; //This line is NOT echo'd because $_SESSION['b'] has not been set. } 
+5
source

In PHP, if the variable does not exist ("unset"), PHP will spit out the E_NOTICE error, create the missing variable and set it to NULL .

If you do not want your scripts to be filled with annoying error messages that leak information about your server and script, then use isset() to check before trying to access the value.

Basically, you ask PHP to get username from $_SESSION , and PHP is "no username "!

+9
source

let's say you set the variable = to false ...

 $variable = false; 

This will not return anything, because it guarantees that the variable is not null, false or empty ('') ...

 if($variable){ echo'something'; } 

This will work no matter what we set the variable to if we set it ... It could be false, str, int, nothing but null!

 if(isset($variable)){ echo'something'; } 
+3
source

Source: https://habr.com/ru/post/1411202/


All Articles