Christian Mayer's Weblog

PHP: '0' as String

‘0’ as a string in PHP is a problem. See this magic trick:

$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:

print strlen($str);

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 ('')? With (bool) you get only strings which are two ‘0’s or longer:

print((bool)$str ? 'OK' : 'FAILED');

Also isset() and empty() will not work:

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.

More Resources

Posted on .
Categories: Programming, Productivity
Tags: PHP, String, length, Null, 0

Categories | RSS Feed | Usage | Imprint
Copyright © 2006 by