Boolean and 0.00

ARG. I encountered another potential issue in PHP that is due to loose types that is common if you are using a database back end.

$amount = 0.00;


$amount = '0.00'; // how data from databases comes

Guess what happens. Well, most people might say both should be TRUE, but that’s not true!

The first one evaluates like this:

  1. 0.00 is the same as 0
  2. 0 is the same as FALSE.
  3. Evaluate the IF condition as FALSE.

The second one evaluates like this:

  1. “0.00” is a string.
  2. A non-empty string is the same as TRUE
  3. Evaluate the IF condition as TRUE.

This is a predictable problem, but highly annoying when working with databases. Most people forget that a float field in the database could equal 0.00, but would evaluate as a TRUE when placed in a condition.

As in, when you get results from the database, the NUMBER 0.00 becomes the WORD “0.00”.

So the lesson here is to make sure you always convert your variables before doing conversions like that. As in:

$amount = '0.00';

Of course, the best solution is always making comparisons explicit:

$amount = '0.00';
if(0 < floatval($amount))