difference between isset, empty, is_null

First, we should know that isset and empty are php language construct while is_null is a function. So you won’t get an E_NOTICE when passing undefined variable to isset or empty but will get an E_NOTICE message while passing undeclared variable to is_null(php issues this error while you use undefined variable in expression or as function parameter, and the undefined variable is evaluated to null, which can be converted to another proper type according to the context). empty() and isset() only accept variable while is_null() can accept any expression including variable.

isset returns true only when the variable is defined and not set to null.

empty() returns true if the variable is not defined, set to null, or other empty values such as ”(not ‘ ‘), 0, FALSE .

is_null returns true if its parameter is null. For undefined variables, is_null returns true with an E_NOTICE because the undefined parameter is evaluted to null. Note that is_null(”) returns false because an empty string is not a null value;

So how to tell if a variable has been defined before? You may think using one or combination of isset, empty(), and is_null can do the work. Actually, it is not a trivial task. You can refer to http://stackoverflow.com/questions/418066/best-way-to-test-for-a-variables-existence-in-php-isset-is-clearly-broken    for the discussion about this problem. In summary, you can use array_key_exists(‘v’, $GLOBALS)  to decide that a global variable v has been defined or not, or use $defined_vars = get_defined_vars();array_key_exists('v', $defined_vars); to check if a local variable is defined or not. The defined or undefined status of a variable is determined at runtime, not compile time. So do not get surprised if an earlier  undefined variable becomes defined when you check it later. A defined variable can also become undefined using unset().

If the variable is set to an empty array (i.e. $var=array()), isset returns true, empty() returns true,and is_null returns false. We often use empty() to check if an array is empty(0 length) because isset cannot differentiate an empty array from an array with some elements.

For an unset array entry, isset returns false, empty() returns true, and is_null returns true(with an E_NOTICE). We often use isset to test whether a variable exists in the _GET or _POST array because empty() returns true even the variable exists(but with an empty value) and is_null issues an unwanted E_NOTICE.

 

Posted in

Leave a Reply