PHP empty Gotcha

Written by James Mansson on July 13, 2013 Categories: PHP

The PHP empty function is described as follows in the documentation:

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Recently, I was working on some code where we used empty to validate a value passed via some XML. The value could be 0, 1 or 2, or it could be left blank. If it was specified, the corresponding database record would be updated with the new value. If it was left blank, that particular field would not be changed. We assumed that empty would detect whether a value had been passed at all, and so were confused that the system failed to set the field to 0 when we passed that value. It transpired that empty would exclude a value of 0 as well, as that evaluates to FALSE in PHP!

No Comments on PHP empty Gotcha

Leave a Reply

Your email address will not be published. Required fields are marked *