PHP: True empty() function to check if a string is empty or zero in length

The strange thing is that the native empty() function of PHP treats a string of ‘0’ as empty:

$str = '0';
echo empty($str) ? 'empty' : 'non-empty';

And it will output ’empty’. Therefore if you need to examine if a string is truly an empty string with zero length, you have to use:

echo strlen($str) == 0 ? 'empty' : 'non-empty';

Or you can use this function:

function isNonEmpty($subject) {
	return !empty($subject) || is_numeric($subject);
}

Which checks if the input string $subject is a numeric value (which makes it non-empty) or if it’s non-empty with empty() function when it’s not a numeric value.

Scroll to Top