How to Check if a Variable is Empty In PHP

PHP



In this article, we go over how to check if a variable is empty or not in PHP.

To check if a variable is empty in PHP, you use the empty function in PHP.

empty($variable)

Below is code that uses an if statement to check if the variable $name is empty or not. If it is empty (contains nothing), the statement, 'The string is empty' is displayed. If it isn't (contains something), it echos the statement, 'The string is not empty'.

if (empty($name)) {
echo 'The string is empty'
}
else {
echo 'The string is not empty';

If the string $name is empty, it will print the first echo statement. If the string is not empty, it will print out the last echo statement.

Example




You have left the name field empty. You must enter a name.

HTML Code

The following code below is the HTML code needed to create the form shown above.



PHP Code

Since the name attribute of the text box in HTML was first_name, the PHP code to generate the program above is:



The code above works very well but there is one problem with this code, though.

It's usually not desired to show that the form hasn't been empty before a user has even clicked the submit button.

For example, when you first reach a form on a website to fill in, you normally don't want to see the message, "You left this field blank" before you even got a chance to fill in the form.

Therefore, it normally is not desired to show the statement, "You have left the name field empty. You must enter a name" until you have clicked the submit button and really left it empty while trying to submit the form.

To remedy this, we need to get data from the submit button to determine if it has been clicked or not. If it has not been clicked, we don't want to display the statement, "You have left the name field empty. You must enter a name", until the user clicks the submit button and left it empty.

Second Example

The example again is shown below.






This code now probably mirrors what you more want.

If a user has now left a field empty and clicked the submit button of the form, then we echo that s/he has left the field blank which needs to be filled. If a user has filled in the field and clicked the submit button, then we echo the name that the user has entered.

The HTML code to build the example right above is unchanged.

PHP Code

The PHP code to build the example above is shown below.





So this is a very easy way of checking if a variable is empty or not in PHP.


HTML Comment Box is loading comments...