PHP: '0' as String

Published in category Programming and Productivity
on Christian Mayer's Weblog.

‘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

Recent Posts

About the Author

Christian is a professional software developer living in Vienna, Austria. He loves coffee and is strongly addicted to music. In his spare time he writes open source software. He is known for developing automatic data processing systems for Debian Linux.