isset()
The isset() function is a built-in function in PHP that checks whether a variable has been set and is not null. It returns true if the variable exists and is
Introduction
The isset() construct is a built-in language construct in PHP that checks whether a variable has been set. It returns true if the variable exists and is not null, and false otherwise. Note that isset() returns true even if the variable's value is 0, false, or an empty string ""; it only returns false for null or unset variables.
Syntax
The syntax of the isset() construct is as follows:
The PHP syntax of isset()
bool isset(mixed $var [, mixed $... ])The construct takes one or more parameters, $var and optional additional parameters separated by commas. Each parameter represents a variable to be checked for being set. The construct returns true if all the variables exist and are not null, and false otherwise.
Example Usage
Here is an example of how to use the isset() construct in PHP:
Example of PHP isset()
<?php
$var1 = "hello";
$var2 = null;
$var3 = 0;
$array = ['key' => 'value'];
if (isset($var1)) {
echo '$var1 is set and is not null' . "\n";
}
if (isset($var2)) {
echo '$var2 is set and is not null' . "\n";
} else {
echo '$var2 is not set or is null' . "\n";
}
if (isset($var3)) {
echo '$var3 is set (value is 0)' . "\n";
}
if (isset($array['key'])) {
echo "Array key 'key' is set" . "\n";
}
?>In this example, we define several variables and an array. We use the isset() construct to check whether each variable or array key is set. The first if statement returns true because $var1 is set. The second if statement returns false because $var2 is null, so the else block executes. The third if statement returns true because $var3 is set to 0 (demonstrating that isset() checks for existence, not truthiness). The fourth if statement returns true because the array key 'key' exists.
Conclusion
The isset() construct is a useful tool for checking whether a variable has been set in PHP. It can be used to ensure that a variable exists before performing operations on it, or to handle set and unset variables in a particular way. By using this construct, developers can ensure that their code is working with the expected data and avoid errors that may occur when working with null values.
Practice
What is the function of the isset() in PHP?