Search code examples
phpif-statementnull

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 ?

Solution

  • 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 set or has an "empty" value (an empty string, zero, etc., see this page for the full list):

    empty($user_id)
    

    If you want to test whether an existing variable contains an empty string, then compare it with an empty string:

    $user_id === ''
    

    If you want to test whether an existing variable contains a value that's considered "not empty" (non-empty string or array, non-zero number, etc..), ! will be sufficient:

    !$user_id