Checking for Variable Existence in PHP

If the variable is declared, but it was not initially assigned any value (in other words, it is not initialized), or if the variable is not defined at all, then it will be problematic for us to use it. For example:

<?php
$a;
echo $a;
?>

When trying to display the value of a variable, we will get a diagnostic message that the variable is not defined:

Warning : Undefined variable $a in C:\localhost\hello.php on line 10

The situation may seem artificial. However, it is not uncommon for variables in PHP to receive some input from outside, such as user input. Accordingly, it becomes necessary to check that these data are defined and available before using the data.

PHP provides a number of built-in functions to test for the existence of a variable.

isset statement

The isset() function allows you to determine whether a variable is initialized or not. If the variable is defined, then isset() returns the value true. If the variable is not defined, then isset() returns false. Also, if the variable has a value, null the function isset() also returns false.

For example:

<?php
$message;
if(isset($message))
    echo $message;
else
    echo "message variable is not defined";
?>

Here the $message variable is not initialized, so the expression isset($message)will return a value of false.

variable message is not defined

Now let the $message variable have an initial value:

$message = "Hello PHP";
if(isset($message))
    echo $message;
else
    echo "message variable is not defined";
    

In this case, the expression isset($message)will return true, so the statement will be executed echo $message:

Hello PHP

However, if the variable is assigned an initial value null, then again it will be considered that this variable is not set:

$message = null;
if(isset($message))
    echo $message;
else
    echo "message variable is not defined";
    

variable message is not defined

empty

The function empty()checks the variable for “emptiness”. An “empty” variable is one whose value is null, 0, false or the empty string – in which case the function empty()returns true:

<?php
$message = "";
if(empty($message))
    echo "message variable is not defined";
else
    echo $message;
?>

Here the variable $messagestores an empty string, so the expression will empty($message) return true.

variable message is not defined

Moreover, if a string contains even at least one space and nothing else ( $message = ” “), then such a string is no longer considered empty.

unset

With the unset() function, we can destroy a variable:

<?php
$a=20;
echo $a; // twenty
unset($a);
echo $a; // error, variable not defined
?>

However, you rarely need to delete a variable like this, because PHP automatically deletes variables when the execution of the context (such as a function) in which those variables are defined ends.