You are currently viewing PHP – The headache of checking if a variable is set!

PHP – The headache of checking if a variable is set!

To check if a variable is set there are two main approaches, depending on the meaning of “set”. Set can mean exists and is not null, but can also mean exists and not empty!

In a code words:

Is $var1 = “” set or not? is $var2 = 0 set or not? this may vary according to the use case. And the main functions we can use are isset() and empty(). However, the behavior of these functions can be a bit tricky.

The empty() and isset() functions in PHP serve different purposes and have distinct behaviors. Understanding the differences between them is crucial for effective PHP programming.

The isset() function returns TRUE if the variable exists and has a value other than NULL, and FALSE otherwise. The empty() function checks if a variable is considered empty. A variable is considered empty if it does not exist or if its value equals FALSE. So the main difference between the two functions is: isset() checks if value is NULL or not and empty() checks if value is FALSE or not. this means that what is “set” may be “empty”.

Examples with variables:

$var1 = “”; // set and empty
$var2 = 0; // set and empty
$var3 = “Hello, World!”; // set and not empty
$var4; // not set and empty
$var5 = “0”; // set and empty

Behavior with Arrays:

Coming to arrays, the isset() function returns TRUE if the array exists and has a value other than NULL, and FALSE otherwise. The empty() function checks if an array is set and contains at least one element even if this element is null.

Examples with arrays:

$array1 = []; // set and empty
$array2 = [NULL,NULL]; // set and not empty
$array3 = [“Hello, World!”]; // set and not empty
$array4; // not set and empty
$array5 = [“0”]; // set and not empty

Leave a Reply