How to check if a variable is empty in PHP - empty()

  • Last update: Apr 3, 2024
  • Views: 22
  • Author: Admin
How to check if a variable is empty in PHP - empty()

Hello colleagues.

Each web developer in his robot is faced with such tasks as determining whether his variable that came from somewhere is empty or not in the PHP programming language. It often happens that some novice developers do not know how to check it, or it does not check it correctly and then there are big problems when it comes to inserting data with this variable into the database.

In today's article, we'll talk about how you can very easily determine whether your variable is empty or not.

 

Article content:

  1. PHP function empty.
  2. Results.

 

1. PHP empty function.

To solve our problem, a php function called empty will help us. The function takes only one required parameter, it can be a number or a string, and even a boolean true or false. The empty function returns a bool type, namely true or false. The function considers a variable empty if the value of the variable is 0, the empty array or variable does not exist, or the value is false.

Function syntax.

empty(mixed $variable): bool

 

Examples.

The first example is when the variable contains an empty array.

php function empty

As you can see, an empty array for the empty function will be considered that the variable is empty.

 

The second example is when the value 0 is stored in a variable.

php function empty

Values ​​of 0 will be considered by the empty function as the absence of a value in the variable.

 

The third example is when an empty string is stored in a variable.

php function empty

An empty string will also be considered the absence of a value.

 

The fourth example is when the value FALSE is stored in a variable.

php function empty

In all examples, the empty function returns TRUE if there is no value in the variable.


 

And now let's see what the function will return in which there will be at least some value.

php function empty

As you can see, if something is stored in the variable, the function will return FALSE, which means that the variable is not empty.


 

2. Results.

As a result of a colleague, today we found out how, using the php empty function, you can very easily and quickly determine whether a variable has any value or not.


 

Thank you all, I hope my article was of some help to you.

SIMILAR ARTICLES