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; if($amount)
$amount = '0.00'; // how data from databases comes if($amount)
Guess what happens. Well, most people might say both should be TRUE, but that’s not true!
The first one evaluates like this:
- 0.00 is the same as 0
- 0 is the same as FALSE.
- Evaluate the IF condition as FALSE.
The second one evaluates like this:
- “0.00” is a string.
- A non-empty string is the same as TRUE
- 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'; if(floatval($amount))
Of course, the best solution is always making comparisons explicit:
$amount = '0.00'; if(0 < floatval($amount))