Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A cool helper function to check if anything is blank in PHP

There are a lot of different ways in PHP using which you can validate if the given value is “blank” or not. The method to validate depends upon the type of value that we’re targetting.

So, for instance, let’s say if you want to check if the value is null, you would use the is_null function of PHP. If you want to check if the given string is empty, you would use the combination of the is_string and trim functions to validate this scenario.

Similarly for numeric and boolean values.

But what if you could combine all of these and conjure up a single function that can validate everything all at once?

Well, recently I have come across one such function that can literally do so.

The blank() swiss army knife function

Braunson Yager shared this function called blank() that can do all the things (that I mentioned above) all at once.

Here’s how it looks like.

/**
 * Determine if the given value is "blank".
 *
 * @param mixed $value
 * @return bool
 */
function blank($value)
{
    if (is_null($value)) {
        return true;
    }

    if (is_string($value)) {
        return trim($value) === '';
    }

    if (is_numeric($value) || is_bool($value)) {
        return false;
    }

    if ($value instanceof Countable) {
        return count($value) === 0;
    }

    return empty($value);
}

As you can tell, you can give the value of any type as an only parameter to this function to validate if it’s blank or not and return a boolean based on the matching scenario.

It even has this obscure scenario that validates arrays and objects using the Countable interface.

A really handy helper function I must say!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?