124

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Timothy Coetzee
  • 5,626
  • 9
  • 34
  • 97
  • 2
    possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Machavity May 12 '15 at 13:01
  • 5
    Note: the really correct answer is the one from scorgn below. – Déjà vu Apr 06 '21 at 08:17
  • [Direct link to scorgn's answer](https://stackoverflow.com/questions/30191521/check-if-a-variable-is-undefined-in-php/66253469#66253469) (user names can change at any time). – Peter Mortensen Sep 19 '21 at 21:20
  • I know this is a PHP question but a note about the JS check: if you use `myVar !== undefined` it will throw a `ReferenceError` if the variable doesn't actually exist. Using `typeof myVar !== 'undefined'` doesn't, so it can be used to check variables that may or may not exist. – BadHorsie Mar 22 '23 at 14:03

8 Answers8

235

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • 2
    `isset()` always returns bool. – VeeeneX May 12 '15 at 12:58
  • Is the boolean cast necessary ? isset(...) does already return bool right ? – Cr3aHal0 May 12 '15 at 12:58
  • 2
    No. It return `true` or `false`. So no need of that casting. – Sougata Bose May 12 '15 at 12:59
  • 1
    you could also do this by using the `empty()` which would return false if it is an empty string. `isset()` will return true if its an empty string, also empty does a isset check internally. – mic May 12 '15 at 13:01
  • 1
    you could also do this: `$isTouch = (bool) $variable;` which will do the same as `isset()` and is maybe a little better since it will work like `empty()`. – mic May 12 '15 at 13:02
  • @mic - IMHO its better to use `isset` or `!empty`, as those don't generate a php warning (in your web log) for an unset variable. `E_NOTICE Undefined variable $variable`. I think you can suppress those warnings, but personally I prefer to not generate them in the first place. – ToolmakerSteve Oct 06 '19 at 13:30
  • 2
    I would argue that !isset(...) does NOT check whether a value is undefined. It checks if it is either undefined or null. I think it's important to note that things can be defined as null. – scorgn Feb 18 '21 at 03:21
  • @scorgn answer explains why this solution may not be what you're looking for. – funder7 Aug 03 '22 at 22:35
27

The isset() function does not check if a variable is defined.

It seems you've specifically stated that you're not looking for isset() in the question. I don't know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.

It's important to realize in programming that null is something. I don't know why it was decided that isset() would return false if the value is null.

To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars(). There is no equivalent to JavaScript's undefined (which is what was shown in the question, no jQuery being used there).

In the following example it will work the same way as JavaScript's undefined check.

$isset = isset($variable);
var_dump($isset); // false

But in this example, it won't work like JavaScript's undefined check.

$variable = null;
$isset = isset($variable);
var_dump($isset); // false

$variable is being defined as null, but the isset() call still fails.

So how do you actually check if a variable is defined? You check the defined variables.

Using get_defined_vars() will return an associative array with keys as variable names and values as the variable values. We still can't use isset(get_defined_vars()['variable']) here because the key could exist and the value still be null, so we have to use array_key_exists('variable', get_defined_vars()).

$variable = null;
$isset = array_key_exists('variable', get_defined_vars());
var_dump($isset); // true


$isset = array_key_exists('otherVariable', get_defined_vars());
var_dump($isset); // false

However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.

scorgn
  • 3,439
  • 2
  • 20
  • 23
  • 11
    This, is the right answer! As for checking if a variable is defined, it's sometimes useful when working on a shi\*y code with global vars all over the place. And why did the PHP folks decide to have *isset()* return *false* if the variable *is* defined and contains *null*... that's another mystery on Earth! – Déjà vu Apr 06 '21 at 08:15
  • 1
    Thanks, this marks the end of my boggling at `isset()`'s curious blind-spot for `null`. As for the "doing something wrong" rationale, after brief consideration I can't point to a non-sketchy scenario for needing to know if a `null` variable exists, but for an array member there are most certainly cases of a meaningful `null`, e.g. when using prepared statements with `PDO`. – Headbank Mar 22 '22 at 15:20
  • 1
    This is only right answer on this page. Learned the hard way. – sandman Apr 22 '22 at 21:19
  • 1
    Nice explanation. `isset` may be working like so for compatibility reasons (it exists since php 4). – funder7 Aug 03 '22 at 22:32
24

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TiDJ
  • 433
  • 1
  • 4
  • 6
  • If we use `$test!==null` without brackets, then what will happened? Will it give error? – G_real Feb 20 '19 at 14:38
  • No, it's ok too. – TiDJ Feb 21 '19 at 15:12
  • Case 1 and 2 will throw a warning. This is not a proper way to check if the value is undefined. – scorgn Feb 18 '21 at 03:24
  • `isset() would return false if the value is null` – Alex78191 Mar 24 '22 at 06:31
  • "The best way is to use isset(). Otherwise you can have an error like "undefined $test"." OP is asking exactly how to check when a variable is undefined! Or when a piece of code will return the warning that you mentioned: probably he wants to intercept such case! – funder7 Aug 03 '22 at 22:38
10

To check if a variable is set you need to use the isset function.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

This code will print:

isset true
isset false

Read more in isset.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ErasmoOliveira
  • 1,416
  • 2
  • 20
  • 40
7

You can use the ternary operator to check whether the value is set by POST/GET or not. Something like this:

$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sumit Thakur
  • 71
  • 1
  • 4
  • 1
    PHP 7.0 introduced the [Null coalescing operator](https://www.php.net/manual/language.operators.comparison.php#language.operators.comparison.coalesce) which is designed for things like this. The code is then `$value1 = $_POST["value1"] ?? "fallback"`. – miile7 Aug 30 '21 at 10:49
  • Nice catch @miile7! – funder7 Aug 03 '22 at 22:40
5

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. Example:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

This code will output "This line is printed, because the $var1 is set."

read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/

thomas
  • 785
  • 8
  • 7
4

JavaScript's 'strict not equal' operator (!==) on comparison with undefined does not result in false on null values.

var createTouch = null;
isTouch = createTouch !== undefined  // true

To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable. If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.

However, you can apply an undefined variable to a reference without any warning:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null !== $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42
  • I'm not sure what the `my_isset` function would accomplish. The only thing it will determine is if a variable is set to null without throwing an error, not if the variable is defined. `$string = 'string'; $is_set = my_isset($string);`In this case `$is_set` would be false, even though it is set to a string. – scorgn Feb 18 '21 at 03:29
  • @scorgn There was a typo. After saying 'If you just use null !== $variable' of course it should not be `===` in the following function. Just edited. – Pinke Helga Jun 13 '21 at 16:16
2

The easiest way to check if a variable or array index exists (is defined) and is not null and is not empty and is not false:

#1

if($variable ?? false) 
    echo '$variable is defined';
else 
    echo '$variable is not defined';

// Result: $variable is not defined

#2

$variable = null;

if($variable ?? false) 
    echo '$variable is not null';
else 
    echo '$variable is null';

// Result: $variable is null

#3

$variable = false;

if($variable ?? false) 
    echo '$variable is not false';
else 
    echo '$variable is false';

// Result: $variable is false

#4

$variable = '';

if($variable ?? false) 
    echo '$variable is not empty';
else 
    echo '$variable is empty';

// Result: $variable is empty
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arash Younesi
  • 1,671
  • 1
  • 14
  • 23
  • 1
    I'd say this solution is the easiest, and probably fine in most cases. It may not be suitable for situations where you need to distinguish between undefined / null / false / true values. – funder7 Aug 03 '22 at 22:46