2ndGAB 2ndGAB - 10 days ago 5
PHP Question

PHP: using empty() for empty string?

I recently discovered this interesting article by Deceze.

But I'm a bit confused by one of its advises:


never use empty or isset for variables that should exist


Using
empty()
is not good choice to test if
$foo = '';
is empty?

Answer

What he means is if you want to check if the string is empty then empty won't do that. Empty can mean false, 0, null. Anything 'falsy'.

E.g. these are all true:

<?php

$string = null;
if (empty($string)) {
    echo "This is true";
}

$string = '';
if (empty($string)) {
    echo "This is true";
}

$string = 0;
if (empty($string)) {
    echo "This is true";
}

If you want to check if the string is an empty string you should do this check for '':

<?php 

$string = '';
if (isset($string) && $string === '') {
    echo "This is true";
}

$string = null;
if (isset($string) && $string === '') {
    echo "This is false";
}
Comments