An empty string does not need to be empty. Just empty enough.

PHP’s “empty” function is a weird little fellow. Basically, it tests if a given variable exists and is not evaluated to false !isset($var) || $var == false And since PHP and has a unique interpretation of what counts as false, I try to replace it with a more explicit counterparts whenever possible. It still creeps up on me sometimes, in places long forgotten, written by a much less careful version of myself. Like a few days ago, when a colleague of mine walked into my office complaining about why our internal system didn’t except his CSV file anymore.

In this CSV, there was a column for a price. And since we are a German speaking company where everybody uses his favorite CSV editor, the CSV files fed to the system vary a lot. A price may be written as ‘12.34’ but also as ‘12,34’, ‘12,34 €’, ‘12,34 Euro’, ‘€12,34’ and so on. As there is really no way to distinguish between ‘1.234’ and ‘1,234’ without knowing the language, I wrote a helper script that tries to guess the correct format (in doubt, use the German notation) and was quite happy as the steady stream of calls complaining about broken CSV imports stopped. That was, until somebody tried to import an item with the price "0": A string containing a single zero. Crash! Why?

Turns out, my code was deliberately throwing an exception whenever someone tried to insert an empty value. Why would you have an empty price after all? In my unit tests this worked great as I was testing it with the string "0.0", which is NOT empty. But the user entered "0" which IS empty. I looked it up, screamed a bit into the pillow I keep on my desk just for these occasions, changed the condition to '' !== $price and added the unit test for "0".

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.