Search Our Site

Our Newsletter

Our Ramblings

A look at some useful PHP functions. isset() vs empty() vs is_null()

Were currently developing a new system in collaboration with our partners at 802 Works – Redefining Wireless. As a part of that, were designing a new system for administering Wireless systems and maximising the marketing leverage that can be gained from them. That job involves having to write quite a lot of PHP pages and scripts. We thought we’d share a short tip on PHP variable declaration.

We’re going to look at the different ways that variables can be empty in this post. PHP has many different operators which can be used to test a variable. Three useful operators used for this are isset(), empty() and is_null(). Each of these operators return a boolean value (either true or false).

Lets take a look at these operators in a little more detail:

isset()

From the bible of PHP, the PHP manual, isset’s job is to “determine if a variable is set and is not NULL”. In other words, it returns true only when the variable is not null.

empty()

Again from the PHP manual, empty’s job is to “determine whether a variable is empty”. In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.

is_null()

Finally, from the PHP manual, is_null’s jobis to “find whether a variable is NULL”. In other words, it returns true only when the variable is null.

You may now be thinking that is_null() is opposite of isset() and , broadly speaking you’d be correct however there is one difference and that is that isset() can be applied to unknown variables, but is_null() only to declared variables.

The table below is an easy reference for what these functions will return for different values.

 

Value of variable ($var) isset($var) empty($var) is_null($var)
“” (an empty string) bool(true) bool(true)  bool(false)
” ” (space) bool(true)  bool(false)  bool(false)
FALSE bool(true) bool(true)  bool(false)
TRUE bool(true)  bool(false)  bool(false)
array() (an empty array) bool(true) bool(true)  bool(false)
NULL  bool(false) bool(true) bool(true)
“0” (0 as a string) bool(true) bool(true)  bool(false)
0 (0 as an integer) bool(true) bool(true)  bool(false)
0.0 (0 as a float) bool(true) bool(true)  bool(false)
var $var; (a variable declared, but without a value)  bool(false) bool(true) bool(true)
NULL byte (“\ 0”) bool(true)  bool(false)  bool(false)

 

I have tested the above values in PHP 7.1.9 which was released on September 1, 2017.

0 Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>