PHP: Be careful with empty()

Be vary careful when using PHP's empty() function. Some code that I came across recently handled configuration of something where each config option was a record in the database. Upon saving, the fields of the form were iterated over and 'empty' fields were ignored and not saved.

However, when a value was 0 it was treated as empty and, therefore, not saved. In this context 0 was meaningful but PHP treated it as empty and ignored it. A better way to handle empty values in that context would have been to simply check for the specific empty string with ===.

The PHP reference for empty() states:

empty() is the opposite of (boolean) var

So when you think you need to use empty() ask yourself what you are really checking. Chances are, you don't want to use empty() anyway.