How to use isset in PHP 8

Description

As with any programming language, variables can lack values. The same goes for PHP 8. Programmers can check whether a variable is null or declared by using the isset function.

isset in PHP 8

isset(mixed $var, mixed ...$vars): bool

The isset function takes at least one paramter $var. If the variable is null or the variable has not been declared yet, it will return true. The isset function also takes a finite number of additional parmaters that should be checked for null or being unset. If you pass multiple variables to the function, it will return true only if all of variables would evalute to true if passed to isset.

Examples

if ( isset($test) ) {
    echo 'Test is set.';
} else {
    echo 'Test is not set.';
}

Test is not set.

Because $test is an undefined variable in this PHP code sample, the isset function returns false.

$test;

if ( isset($test) ) {
    echo 'Test is set.';
} else {
    echo 'Test is not set.';
}

Test is not set.

Here the variable may be in scope, but it hasn't been declared yet. As a result, the isset function returns false.

$test = 0;

if ( isset($test) ) {
    echo 'Test is set.';
} else {
    echo 'Test is not set.';
}

Test is set.

Finally, $test is declared with the value 0. The isset function correctly returns true because the variable has been declared. Also note, 0 is not equal to null. Hence, it returns true.

$test = null;

if ( isset($test) ) {
    echo 'Test is set.';
} else {
    echo 'Test is not set.';
}

Test is not set.

Last but not least, if we initialize the $test variable with null, the isset function returns false.

In order to check if a variable is just null, you would use the function is_null function in PHP 8.

$test1 = 0;
$test2;
if ( isset($test1, $test2) ) {
    echo 'Tests are set.';
} else {
    echo 'Tests are not set.';
}

Tests are not set.

Lastly, if we initialize the $test1 variable with 0 and add an additional $test2 variable, the isset function returns false as not all variable are declared.