Monday, 23 September 2013

PHP empty(), what is empty?

Using the PHP empty(); function can be really helpful in development but also is one of the functions which cause a lot of errors, especially when starting out with PHP, as what PHP considers to be empty isn't as obvious as it should be.

What does empty(); consider to be empty?

Here's a list of what the PHP empty(); function considers to be empty:
  • "" - An empty string
  • 0 - The integer 0, this can catch people out.
  • 0.0 - The floating point 0.0
  • "0" - The string 0
  • false - Boolean false value
  • array() - An empty array
  • null - A null value

Common mistakes

Probably the most common one that catches people out is either the integer 0 or string 0 being considered empty, even though it looks like there's a value in there. Possibly one of the most common places developers get caught out with this is validation, if you're validating a form field with a question like "How many cars are in your household," and the user enters "0" when you validate with PHP to check that they've answered the question by using only the empty(); function on the value of that field then it'll tell you it's empty even though the user has entered a value.

How to use empty();

I thought I'd also give a quick example of how to use empty(); encase someone reading this hasn't heard of this function before. It's really simple.

$val_field = empty($form_name); // $val_field will either be true or false depending on if $form_name is considered to be empty or not

Further reading

1 comment: