Christian Mayer's Weblog

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:

print strlen($str);

So you can’t check with ==. You must take ===. In other words == != ===.

print($str === '0' ? 'OK' : 'FAILED'); // will print "FAILED".

Yesss!

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

if($str){

because it’s pretty nice to read and simple to write. But it won’t work for ‘0’. So I guess

if(strlen($str)){

is more fail-safe.


Simple code is hard to write.


More Resources

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

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