How to use isset vs just $_SESSION?


#1

What is the difference between if (!isset($_SESSION[‘u_uid’])) and if (!$_SESSION[‘u_uid’])? From my understanding, isset means whether it is set and I would use this to check to see if the form has been set or not? So basically, anything with a form input should have isset?


#2

Hi there,

isset is exactly what the name of the function suggests, was this $var set and does it have a different value than NULL (click me!) a plain check, if (!$var) does simply: If NOT $var (if the value of $var is false)

As for you other question, in general, it is good practice to always check if a required variable in a form is set before assuming it is set.


#3

Thanks for the quick reply… So, I should always use isset just to be safe?


#4

Example:
My form has the fields: FirstName, Addition, LastName.

Requirements for submitting:

FirstName is required
LastName is required

So I would do:

if (isset($_POST[‘FirstName’])) {
$_POST[‘FirstName’]
}
if (isset($_POST[‘LastName’])) {
$_POST[‘LastName’]
}
$addition = $_POST[‘addition’] ?? null; // Use $_POST[‘addition’] if set otherwise $addition is NULL

So, I would only use isset(); if the value is required for running your code, otherwise you can set it safely to NULL yourself (even if it isn’t set) or any other default value you like to uphold.