This article demonstrates how to check if a string is empty in PHP.

1. Using identity operator

The equality operator ($a == $b) returns true if $a is equal to $b after type conversion. When a variable is compared against an empty string using the equality operator (==), it returns true when the variable is either empty, false, null, or not set.

Download  Run Code

 
You might want to check the type along with the value while comparing a variable against an empty string. This can be done using the equality comparison operators (== and !=), where type juggling doesn’t happen. The identity comparison $a === $b returns true if $a is equal to $b and they are of the same type.

Download  Run Code

2. Using strlen() function

Alternatively, you can use the strlen() function to check for empty strings in PHP, which returns the string’s length. However, it returns length 0 not only for empty strings, but for false, null, and unset variables as well. Therefore, you should always check the variable’s type before invoking this function. This can be done using the is_string() function, which returns true if and only if the specified value is of type string.

Download  Run Code

 
You may also use the preg_match() function with the \S regular expression, which matches any non-whitespace character. For example,

Download  Run Code

3. Using empty() function

Finally, if you need to check a variable against all falsey values (like false, 0, "", NULL, array(), etc.), you can use the empty() function. You may also use the logical negation operator (!), which returns a boolean value that is opposite of its operand’s boolean representation.

Download  Run Code

That’s all about checking if a string is empty in PHP.