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.
Frequently Asked:
- Check if String contains Numbers in PHP
- Check if a String Starts With a Substring in PHP
- Check if String is Binary in PHP
- Check if String is an Integer in PHP
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.