Check if a string is empty in PHP
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $var = ""; if ($var == "") { echo 'The value is either empty, false, null, or not set'; } /* Output: The value is either empty, false, null, or not set */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $var = ""; if ($var === "") { echo 'The value is an empty string'; } /* Output: The value is an empty string */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $var = ""; if (is_string($var) && !strlen($var)) { echo 'The value is an empty string'; } /* Output: The value is an empty string */ ?> |
You may also use the preg_match() function with the \S regular expression, which matches any non-whitespace character. For example,
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $var = "0"; if (is_string($var) && !preg_match('/\S/', $var)) { echo 'The value is an empty string'; } /* Output: The value is an empty string */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $var = 0; if (empty($var)) { echo 'The Variable is falsey'; } /* Output: The Variable is falsey */ ?> |
That’s all about checking if a string is empty in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)