Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable is undefined in PHP

Tags:

php

Consider this JavaScript statement:

isTouch = document.createTouch !== undefined 

I would like to know if we have a similar statement in PHP, not being isset(), but literally checking for an undefined value. Something like:

$isTouch != ""

Is there something similar as the above in PHP?

like image 992
Timothy Coetzee Avatar asked May 12 '15 12:05

Timothy Coetzee


People also ask

How check variable is undefined in PHP?

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.

How do you know if a variable is undefined?

So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .

Is NULL or undefined PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .

How check variable is NULL in PHP?

To check if the variable is NULL, use the PHP is_null() function. The is_null() function is used to test whether the variable is NULL or not. The is_null() function returns TRUE if the variable is null, FALSE otherwise. There is only one value of type NULL, and it is the case-insensitive constant NULL.


2 Answers

You can use -

$isTouch = isset($variable); 

It will return true if the $variable is defined. If the variable is not defined it will return false.

Note: It returns TRUE if the variable exists and has a value other than NULL, FALSE otherwise.

If you want to check for false, 0, etc., you can then use empty() -

$isTouch = empty($variable); 

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)
like image 107
Sougata Bose Avatar answered Sep 23 '22 11:09

Sougata Bose


Another way is simply:

if($test){     echo "Yes 1"; } if(!is_null($test)){     echo "Yes 2"; }  $test = "hello";  if($test){     echo "Yes 3"; } 

Will return:

"Yes 3" 

The best way is to use isset(). Otherwise you can have an error like "undefined $test".

You can do it like this:

if(isset($test) && ($test!==null)) 

You'll not have any error, because the first condition isn't accepted.

like image 25
TiDJ Avatar answered Sep 23 '22 11:09

TiDJ