Languages which do type-coercion are generally setting users up for failure. At some point, you'll make some assumption about your inputs, and then type-coercion kicks in and changes what you expect. We see this all the time in JavaScript, and of course, in PHP. PHP booleans, for example, can surprise you: 0
is false, which is a common enough assumption, but so is "0"
- the string zero. As are empty arrays.
But what if you wanted more control over it? Peter sends us this PHP he found:
$trueFalse = array('false', 'true');
This creates the trueFalse
array such that it holds the strings false
and true
. These are, in PHP-land, both true. But let's set that aside, and look at how this array gets used:
$boolStr = @trueFalse[$some->integer->property];
Yes, this is their approach to converting a boolean to a user-readable string. Which, if you don't know much about PHP, feels necessary. If you echo
a boolean, it prints out as either a "1" or nothing. You need to use the function var_export
, var_dump
, or do an sprintf
, or a ternary, a lot of other weird workarounds. But this solution also conceals another problem: a boolean variable which is true may be any nonzero value- which would break when we try and index the array by that.
I'll let Peter share his thoughts:
I actually cannot determine if this is brilliant™ or just plain stupid, but i do love the fact that the array is called trueFalse while the values in order are false and true... does that mean that true is false and false is true?
No, Peter, I don't think it means that, but I also don't think it's plain stupid. This is, despite its simplicity, advanced stupid.
![](https://thedailywtf.com/images/inedo/buildmaster-icon.png)