Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is undefined a data-type in php?

Is undefined a data-type in php? Also, how does one check for it (on a variable, is or is not undefined)?

like image 861
Colin Brogan Avatar asked Apr 22 '26 05:04

Colin Brogan


2 Answers

There is no "undefined" data type in PHP. You can check for a variable being set with isset, but this cannot distinguish between a variable not being set at all and it having a null value:

var_dump(isset($noSuchVariable)); // false

$nullVariable = null;
var_dump(isset($nullVariable)); // also false

However, there is a trick you can use with compact that allows you to determine if a variable has been defined, even if its value is null:

var_dump(!!compact('noSuchVariable')); // false
var_dump(!!compact('nullVariable')); // true

Live example.

Both isset and the compact trick also work for multiple variables at once (use a comma-separated list).

You can easily distinguish between a null value and total absence when dealing with array keys:

$array = array('nullKey' => null);

var_dump(isset($array['nullKey'])); // false
var_dump(array_key_exists($array, 'nullKey')); // true

Live example.

When dealing with object properties there is also property_exists, which is the equivalent of array_key_exists for objects.

like image 84
Jon Avatar answered Apr 24 '26 19:04

Jon


No, undefined is not a data type in PHP. You check if a variable is set (i.e. previously defined and not null) in PHP with isset():

if( isset( $foo)) { 
    echo "Foo = $foo\n";
} else {
    echo "Foo is not set!\n";
}

From the docs, isset() will:

Determine if a variable is set and is not NULL.

like image 25
nickb Avatar answered Apr 24 '26 17:04

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!