PHP: '0' as String
‘0’ as a string in PHP is a problem. See this magic trick:
<?php $str = '000'; print($str == '0' ? 'OK' : 'FAILED');
What’s your first thought what will be printed? I guess you would say it prints FAILED. But try it for yourself. It will print OK.
Only the string length is what everybody would expect, 3:
So you can’t check with
==. You must take
===. In other words
print($str === '0' ? 'OK' : 'FAILED'); // will print "FAILED".
But wait, what if you want that ‘0’ and ‘00’ and ‘000’ and ‘0000’ and ‘00000’ and … always returns
true but not an empty string (
(bool) you get only strings which are two ‘0’s or longer:
print((bool)$str ? 'OK' : 'FAILED');
empty() will not work:
falseif a variable doesn’t exist or the variable is
The best way is to check the string length. The most times I use
because it’s pretty nice to read and simple to write. But it won’t work for ‘0’. So I guess
is more fail-safe.
Simple code is hard to write.