Check if a String is Empty in PHP

This tutorial will discuss about unique ways to check if a string is empty in php.

Table Of Contents

Method 1: Using empty()

PHP Provides a function empty(), which accepts a string value as an argument, and return true if that string is empty. But before that we need to make sure that that string variable exists and its value is set.

In the below example, we will create a string object and then we will check if it is empty or not.

Let’s see the complete example,

<?php
$strValue = "";

// Check if variable is set and empty
if (isset($strValue) && empty($strValue)) {
    echo "The string is empty.";
} else {
    echo "The string is not empty.";
}
?>

Output

The string is empty.

Method 2: Using strlen()

The strlen() function in PHP accepts a string as an argument and returns the number of characters in that string. If strlen() function returns 0, then it means that the given string is empty.

In the below example, we will create a string object and then we will check if it is empty or not.

Let’s see the complete example,

<?php
$strValue = "";

// Check if string is empty
if (strlen($strValue) === 0) {
    echo "The string is empty.";
} else {
    echo "The string is not empty.";
}
?>

Output

The string is empty.

Summary

We learned about two different ways to check if a string is empty or not in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top