Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?
like image 268
ZeroSuf3r Avatar asked Jan 08 '12 12:01

ZeroSuf3r


People also ask

How check if variable is empty shell?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

How do you check if a variable is empty in C++?

To check if a string is empty or not, we can use the built-in empty() function in C++. The empty() function returns 1 if string is empty or it returns 0 if string is not empty. Similarly, we can also use the length() function to check if a given string is empty or not.


2 Answers

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 
like image 94
Rob W Avatar answered Oct 04 '22 11:10

Rob W


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.

like image 22
Jens Avatar answered Oct 04 '22 13:10

Jens