The problem of untyped languages: PHP empty() function

There are a few programming languages that work nicely without typing (for example, Javascript or PHP). They have their advantages, but I just can't put them on the same level of a strongly typed language like C# or Java, and here is an example that any PHP developer will suffer sooner or later.

In PHP, we have a function to determine if a variable has no value, empty(). But most experienced PHP developers will advise you to never use it. Why? Let's see an example:

<?php
$test1 = '0';
$test2 = false;

if (!empty($test1)) {
echo $test1.'<br />';
} else {
echo 'test1 is empty<br />';
}
if (!empty($test2)) {
if($test2) {
echo 'true';
} else {
echo 'false';
}
} else {
echo 'test2 is empty<br />';
}

?>

This code looks correct. We create a string variable ($test1) and a boolean one ($test2). We check their values and output different messages depending on their content. But can you guess the output?

"testx is empty" in both cases.
The reason is that, in PHP, false equals empty too, and as there is no typing, a string containing only a zero will be interpreted as a false (exactly, like a "zero byte", "\0"), and thus, empty() will return true.

So, what's a correct way to check for empty variables AND handle this special cases? Another small example:

<?php

$test1 = '0';
$test2 = false;


if (isset($test1) && $test1 !== '') {
echo $test1.'<br />';
} else {
echo 'test1 is empty<br />';
}
if (isset($test2) && $test2 !== '') {
if($test2) {
echo 'true';
} else {
echo 'false';
}
} else {
echo 'test2 is empty<br />';
}
?>

The isset() function works much better, as checks for a specific null value. Using === or !== we force that both parameters have to be of the same type (although not typed, PHP supports casting and type checks to aid us). And finally, as PHP implements lazy evaluation, we don't need to worry about comparing a null against a string because isset() will catch it first.

As with most programming languages, there are ways to do things right. But I can't stop thinking why the PHP team doesn't at least improves the code of the empty() function to make it work properly and instead add new functions. Compatibility with crap only makes crap still available, doesn't fixes it.

Comments?

Posted by Kartones on 2009-03-30