check if variable empty

if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
    $user_id = '-1';
    $user_name = NULL;
    $user_logged = NULL;
}
if ($user_admin == NULL) {
    $user_admin = NULL;
}
  1. Is there any shortest way to do it ?
  2. And if i right, it should be tested with is_null?
  3. It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?

If you want to test whether a variable is really NULL, use the identity operator:

$user_id === NULL  // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)

If you want to check whether a variable is not set:

!isset($user_id)

Or if the variable is not empty, an empty string, zero, ..:

empty($user_id)

If you want to test whether a variable is not an empty string, ! will also be sufficient:

!$user_id

You can check if it's not set (or empty) in a number of ways.

if (!$var){ }

Or:

if ($var === null){ } // This checks if the variable, by type, IS null.

Or:

if (empty($var)){ }

You can check if it's declared with:

if (!isset($var)){ }

Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.


empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

<?php
    $val = 0;
    //evaluates to true because $var is empty
    if (empty($val)) {
        echo '$val is either 0, empty, or not set at all';
    }
    //evaluates to true because $VAR IS SET
    if (isset($val)) {
        echo '$val is set even though it is empty';
    }
    ?>

Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following

if (!empty($var) && is_null($var))

Note the PHP manual

variable is considered empty if it does not exist or if its value equals FALSE

As opposed to being null which is handy here!