If you’re testing for an empty string in PHP you could be forgiven for using the empty()
function. However, exercise caution as empty()
may not do what you think it does.
PHP treats 0 and ’0′ as empty. Take the following:
$var = '0';
if(empty($var)) {
echo 'true';
}
else {
echo 'false';
}
The above will echo true even through $var
is a string with a single character in. Empty space, however, is not considered empty.
$var = ' ';
if(empty($var)) {
echo 'true';
}
else {
echo 'false';
}
The above will echo false. This can be a little confusing although it does treat null as empty—which is what you’d probably expect. Perhaps a better function would be:
function strictEmpty($var) {
// Delete this line if you want space(s) to count as not empty
$var = trim($var);
if(isset($var) === true && $var === '') {
// It's empty
}
else {
// It's not empty
}
}
isset()
checks that the variable is set and not null. $var !== ''
is used instead of $var != ''
as the latter is essentially the same as calling empty()
.
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from
Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.