OneBite.Dev - Coding blog in a bite size

Check If A String Is Empty In PHP

Code snippet for how to Check If A String Is Empty In PHP with sample and detail explanation

In this article, we are going to delve into how to check whether a string is empty in PHP. This is an important programming hurdle that you will often come across when developing PHP applications.

Code snippet for Empty string check in PHP

In PHP, to check if a string is empty, we typically use the empty() function. The empty() function in PHP checks whether a variable is empty or not. If the variable is not set, or if it’s an empty string, or zero, or ‘0’, or null, or false, then the function returns true, which denotes that the variable is empty.

Here’s a code example:

<?php
    $str = "";
    if (empty($str)) {
        echo "The string is empty";
    } else {
        echo "The string is not empty";
    }
?>

Code Explanation for Empty string check in PHP

In the above PHP script, we define a variable $str and assign an empty string value to it.

The if statement checks whether the $str string is empty by using the empty() function. The empty() function in PHP checks if a variable is empty - if it doesn’t exist or if its value equals NULL, or if it’s an empty string, or zero, the function will return true.

In this case, because $str is an empty string, the empty() function returns true and the if statement outputs “The string is empty”. If the $str was not empty, the code within the else statement would have been executed, and you would see “The string is not empty” as output.

Remember that empty() will also return true if the variable is set to zero (‘0’) or false, not just null or empty strings. So, ensure that this behavior is aligned with the needs of your script. Consider combining empty() with isset(), or !== '', if you need to discern zero (‘0’) or false from a truly empty string.

And that, in a nutshell, is how you check if a string is empty in PHP.

php