Whitespace and PHP’s empty function.

The PHP function empty is often used to check if a particular variable is empty or not (duh). First, it checks to see if the variable exists. If it does exist, then it checks to see if the variable is a “falsey” value. However, there is a bit of caveat that you should be aware of. Particularly, in regards to user-submitted string values.

Take the following code for example:

<?php

$whiteSpaceString = " ";
if(!empty($whiteSpaceString)){
    echo 'Not Empty!';
}

If you run the code above, you’ll see that the output is “Not Empty!”, despite the fact that the string is empty (for all intents and purposes). This is because it contains a single whitespace character.

To protect yourself against situations where whitespace “fools” PHP’s empty function, you will need to strip out whitespace characters from strings before you attempt to check them:

<?php

//Create string with whitespace.
$str = ' ';

//If $str exists, trim it.
$str = isset($str) ? trim($str) : false;

if(!empty($str)){
    echo 'Not Empty!';
} 
else{
    echo 'Empty!';
}

Note that if you attempt to use the trim function inside the empty function, you will be met with a nasty fatal error. Example code:

if(!empty(trim($str))){
    echo 'Not Empty!';
}

The above piece of code will result in: “Fatal error: Can’t use function return value in write context.”