PHP ISSET() FUNCTION
- The isset() function is a built-in function of PHP, which is used to determine that a variable is set or not.
- If a variable is considered set, means the variable is declared and has a different value from the NULL.
- In short, it checks that the variable is declared and not null.
- This function returns true if the variable is not null, otherwise it returns false.
Syntax:
- isset (mixed variable) or
- isset (mixed variable,mixed variable1) or
- isset (mixed variable, ….)
Mixed denotes that the parameter may be multiple types.
This function accepts one or more
parameters, but it must contain atleast one parameter.
variable (required) - It is necessary to
pass this parameter to this function because it holds that variable/element,
which is to be checked.
Return Values
The isset() function returns a boolean
value: It may be either true or false.
If the variable exists and does not
contain a NULL value, it returns TRUE otherwise, it returns FALSE.
Example 1
<?php
$var1 = 'test';
if(isset($var1)) {
echo "The variable $var1 is set, so it will print.
</br>";
var_dump(isset($var1));
} ?>
Output
The variable test is set, so it will
print.
bool(true)
Example 2: Difference between null character and NULL constant
<?php
$x = 9;
//TRUE because $x is set
if ($resultX = isset ($x)) {
echo "Variable 'x' is set.";
}
echo var_dump(isset($resultX)). "</br>";
$y = NULL;
//False because $y is Null
if (isset ($y)) {
echo "Variable 'y' is not set.";
}
echo var_dump(isset($y)). "</br>";
$z ='\0';
//TRUE because \0 and NULL are treated different
if ($resultZ = isset ($z)) {
echo "Variable 'z' is set.";
}
echo var_dump(isset($resultZ));
?>
Output
Variable 'x' is set. bool(true)
bool(false)
Variable 'z' is set. bool(true)
Example 3: Use of unset()
In this example, we will use the unset()
function to unset the variable.
<?php
$var1 = 'test';
$var2 = 'another test';
if (isset($var1) && isset( $var2)) {
echo "It will print because variables are set.
</br>";
var_dump (isset($var1));
var_dump (isset($var2));
}
unset ($var1);
unset ($var2);
echo "</br> </br>Variables after unset:
</br>";
var_dump (isset($var1));
var_dump (isset($var2));
?>
Output
It will print because variables are set.
bool(true) bool(true)
Variables after unset:
bool(false) bool(false)
Example 4: Difference between isset and !empty
The isset() and !empty() functions are
operated same and both return same results.
The only difference between them is that
if the variable is not present, the !empty() function does not generate any
warning.
<?php
$valiable1 = '0';
//check the isset() function
if (isset ($variable1)) {
print_r($variable1 . " is checked by isset() function");
}
echo "</br>";
$variable2 = 1;
//check the !empty() function
if (!emptyempty ($variable2)) {
print_r($variable2 . " is checked by !empty() function");
}
?>
Output
0 is checked by isset() function
1 is checked by !empty() function
Example 5: Checking multiple variables
<?php
$var_test1 = '';
$var_test2 = '';
if (isset ($var_test1, $var_test2)) {
echo "Variables are declared and also not null.";
} else {
echo "Variables are not set or null";
}
?>
Output
Variables are declared and also not null.
Example 5: isset() to check session
variable
<?php
$user = 'PHP101';
$_SESSION['userid'] = $user;
if (isset($_SESSION['userid']) &&
!emptyempty($_SESSION['userid'])) {
echo " Session is available, Welcome to $_SESSION[userid]
";
} else {
echo " No Session, Please Login ";
}
?>
Output
Session is available, Welcome to PHP101How isset() Works
Single Variable Check
$name = "John";
if (isset($name)) {
echo "The variable 'name' is set.";
} else {
echo "The variable 'name' is not set.";
}
Output: The variable 'name' is set.
In this example, isset($name) checks if the variable $name is set and is not null. Since $name is set to "John", isset($name) returns true.
Multiple Variables Check
$name = "John";
$age = null;
if (isset($name, $age)) {
echo "Both variables 'name' and 'age' are set.";
} else {
echo "Either 'name' or 'age' is not set.";
}
Output: Either 'name' or 'age' is not set.
In this example, isset($name, $age) checks if both $name and $age are set and are not null. Since $age is null, isset($name, $age) returns false.
Variable Not Set
if (isset($name)) {
echo "The variable 'name' is set.";
} else {
echo "The variable 'name' is not set.";
}
Output: The variable 'name' is not set.
In this example, since $name has not been declared, isset($name) returns false.
Practical Use Cases
Form Data Handling
if (isset($_POST['submit'])) {
// Handle form submission
$name = $_POST['name'];
$email = $_POST['email'];
// Process the data
}
Here, isset($_POST['submit']) checks if the form was submitted.
Conditional Variable Checking
$user = isset($_GET['user']) ? $_GET['user'] : 'guest';
echo "Hello, $user!";
This example uses the ternary operator to check if the user parameter is set in the URL query string. If it is, it assigns its value to $user; otherwise, it assigns the default value 'guest'.
Array Element Check
$arr = ['name' => 'John', 'age' => 25];
if (isset($arr['name'])) {
echo "Name is set.";
}
isset($arr['name']) checks if the 'name' key exists in the array and is not null.
Check if a Variable is Set
$var = "Hello, World!";
if (isset($var)) {
echo "Variable is set.";
} else {
echo "Variable is not set.";
}
Output:
Variable is set.
isset($var) returns true because $var is set to "Hello, World!".
Check if a Variable is Unset
if (isset($undefinedVar)) {
echo "Variable is set.";
} else {
echo "Variable is not set.";
}
Output:
Variable is not set.
isset($undefinedVar) returns false because $undefinedVar is not defined.
Multiple Variables
Check Multiple Variables
$var1 = "Hello";
$var2 = null;
if (isset($var1, $var2)) {
echo "Both variables are set.";
} else {
echo "One or both variables are not set.";
}
Output:
One or both variables are not set.
isset($var1, $var2) returns false because $var2 is null.
Check if Array Key is Set
$arr = array('name' => 'John', 'age' => 25);
if (isset($arr['name'])) {
echo "Name is set.";
} else {
echo "Name is not set.";
}
Output:
Name is set.
isset($arr['name']) returns true because the 'name' key exists in the array.
Check if Nested Array Key is Set
$arr = array('user' => array('name' => 'John', 'age' => 25));
if (isset($arr['user']['name'])) {
echo "User name is set.";
} else {
echo "User name is not set.";
}
Output:
User name is set.
isset($arr['user']['name']) returns true because the 'name' key exists in the nested array.
Objects
Check if Object Property is Set
class User {
public $name;
}
$user = new User();
$user->name = "John";
if (isset($user->name)) {
echo "User name is set.";
} else {
echo "User name is not set.";
}
Output:
User name is set.
isset($user->name) returns true because the name property of the $user object is set.
Form Data Handling
Check if Form Data is Set
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
echo "Username and password are set.";
} else {
echo "Username and password are required.";
}
}
This example checks if the username and password fields are set in the POST request before processing them.
Session Variables
Check if Session Variable is Set
session_start();
if (isset($_SESSION['user_id'])) {
echo "User is logged in.";
} else {
echo "User is not logged in.";
}
This example checks if the user_id session variable is set to determine if a user is logged in.
Default Values
Set Default Value if Variable is Not Set
$name = isset($name) ? $name : 'Guest';
echo "Hello, $name!";
Output:
Hello, Guest!
This example uses the ternary operator to assign a default value to $name if it is not set.
Default Value Using Null Coalescing Operator (PHP 7+)
$name = $_GET['name'] ?? 'Guest';
echo "Hello, $name!";
Output:
Hello, Guest!
This example uses the null coalescing operator (??) to assign a default value to $name if it is not set.
Conditional Logic
Complex Conditional Check
$data = array('username' => 'john', 'email' => 'john@example.com');
if (isset($data['username']) && isset($data['email'])) {
echo "Username and email are set.";
} else {
echo "Username or email is not set.";
}
Output: Username and email are set.
This example checks if both 'username' and 'email' keys are set in the $data array.
Important Points
- isset() returns false if the variable is null.
- isset() can be used to check multiple variables; if any of the variables are not set or are null, it returns false.
- If a variable is declared but not initialized, isset() returns false.
- It does not generate a warning if the variable does not exist.
- In summary, isset() is a useful function for checking the existence and non-null status of variables in PHP, helping to prevent errors and manage data more effectively.
isset() is used to check if a variable is set and is not null.
It does not generate a warning if the variable does not exist, making it a safe check.
It is useful for form data validation, session management, default value assignment, and conditional logic.
It can check multiple variables at once, returning true only if all variables are set and not null.
These examples illustrate the versatility of the isset() function and how it can be used in various scenarios to ensure that variables are set before they are used in your code.
The empty() function in PHP
The empty() function in PHP is used to check whether a variable is empty.
A variable is considered empty if it does not exist or if its value is considered "empty."
The following values are considered empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- $var (a variable declared but without a value)
Syntax
empty(mixed $var): bool
$var: The variable to check.
How empty() Works
Checking an Empty String
$str = "";
if (empty($str)) {
echo "The string is empty.";
} else {
echo "The string is not empty.";
}
Output:
The string is empty.
empty($str) returns true because the string is empty.
Checking a Zero Integer
$num = 0;
if (empty($num)) {
echo "The number is empty.";
} else {
echo "The number is not empty.";
}
Output:
The number is empty.
empty($num) returns true because the value 0 is considered empty.
Checking an Undefined Variable
if (empty($undefinedVar)) {
echo "The variable is empty.";
} else {
echo "The variable is not empty.";
}
Output:
The variable is empty.
empty($undefinedVar) returns true because the variable is not set.
Checking an Array
$arr = array();
if (empty($arr)) {
echo "The array is empty.";
} else {
echo "The array is not empty.";
}
Output:
The array is empty.
empty($arr) returns true because the array is empty.
Checking a Non-Empty String
$str = "Hello";
if (empty($str)) {
echo "The string is empty.";
} else {
echo "The string is not empty.";
}
Output:
The string is not empty.
empty($str) returns false because the string "Hello" is not empty.
Checking a Boolean False
$flag = false;
if (empty($flag)) {
echo "The flag is empty.";
} else {
echo "The flag is not empty.";
}
Output:
The flag is empty.
empty($flag) returns true because false is considered empty.
Checking a Non-Empty Array
$arr = array(1, 2, 3);
if (empty($arr)) {
echo "The array is empty.";
} else {
echo "The array is not empty.";
}
Output:
The array is not empty.
empty($arr) returns false because the array has elements.
Checking an Object Property
class User {
public $name;
}
$user = new User();
$user->name = "John";
if (empty($user->name)) {
echo "The name property is empty.";
} else {
echo "The name property is not empty.";
}
Output:
The name property is not empty.
empty($user->name) returns false because the name property is set to "John".
Practical Use Cases
Form Data Validation
if (empty($_POST['username']) || empty($_POST['password'])) {
echo "Username and password are required.";
} else {
// Process the form data
}
This example checks if the username or password fields in a form are empty.
Default Value Assignment
$username = !empty($_POST['username']) ? $_POST['username'] : 'guest';
echo "Hello, $username!";
This example assigns a default value of 'guest' if $_POST['username'] is empty.
Conditional Logic
if (!empty($data)) {
// Process the data
} else {
echo "No data available.";
}
This example processes the data only if it is not empty.
Complex Use Cases
Form Handling with Multiple Fields
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$errors = array();
if (empty($_POST['username'])) {
$errors[] = "Username is required.";
}
if (empty($_POST['email'])) {
$errors[] = "Email is required.";
}
if (empty($_POST['password'])) {
$errors[] = "Password is required.";
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p>$error</p>";
}
} else {
// Process the form data
}
}
This example checks multiple form fields and collects errors if any fields are empty. It then displays the errors or processes the form data.
Checking Session Variables
session_start();
if (empty($_SESSION['user_id'])) {
echo "You are not logged in.";
} else {
echo "Welcome, user ID: " . $_SESSION['user_id'];
}
This example checks if the user_id session variable is empty to determine if a user is logged in.
Default Configuration Values
$config = array(
'db_host' => 'localhost',
'db_user' => '',
'db_pass' => ''
);
$db_user = !empty($config['db_user']) ? $config['db_user'] : 'root';
$db_pass = !empty($config['db_pass']) ? $config['db_pass'] : '';
echo "Database User: $db_user<br>";
echo "Database Password: $db_pass<br>";
Output:
Database User: root
Database Password:
This example checks configuration values and assigns default values if they are empty.
Conditional Initialization
$data = !empty($_GET['data']) ? $_GET['data'] : 'default data';
echo "Data: $data";
This example checks if the data parameter is present in the URL query string. If it is empty, it assigns a default value.
Important Points
- empty() can be used with any variable type.
- It does not generate a warning if the variable does not exist, making it a safe check.
- empty() is often used in form validation and conditional logic to ensure that required data is provided or to assign default values.
- In summary, empty() is a useful function for checking whether a variable is empty in PHP, helping to manage data validation and conditional processing effectively.
- Safety: empty() can be used safely without generating warnings if the variable does not exist.
- Versatility: It can check various types, including strings, numbers, arrays, objects, and even unset variables.
- Use Cases: Commonly used in form validation, session management, default value assignment, and conditional logic.
- In conclusion, empty() is a highly versatile and essential function in PHP for checking whether variables are empty, helping developers manage data more effectively and prevent errors.
Some Complex Examples from Isset and empty
Example 1: Basic Form Handling with isset()
Form HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP Code (process.php):
<?php
// Step 1: Check if the form was submitted
if (isset($_POST['submit'])) {
// Step 2: Retrieve the form data
$username = $_POST['username'];
$email = $_POST['email'];
// Step 3: Display the form data
echo "Username: $username<br>";
echo "Email: $email<br>";
} else {
echo "Form not submitted.";
}
?>
Code Explanation:
Form Submission Check:
isset($_POST['submit']) checks if the "Submit" button was clicked. If the form was submitted, it proceeds; otherwise, it shows "Form not submitted."
Retrieve Data:
$_POST['username'] and $_POST['email'] fetch the values from the form fields.
Display Data:
The retrieved values are displayed on the page.
Example 2: Basic Form Handling with empty()
Form HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Code (process.php):
<?php
// Step 1: Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Step 2: Retrieve form data
$username = $_POST['username'];
$email = $_POST['email'];
// Step 3: Check if fields are empty
if (empty($username)) {
echo "Username is required.<br>";
} else {
echo "Username: $username<br>";
}
if (empty($email)) {
echo "Email is required.<br>";
} else {
echo "Email: $email<br>";
}
}
?>
Code Explanation:
Form Submission Check:
$_SERVER["REQUEST_METHOD"] == "POST" checks if the form was submitted via POST.
Retrieve Data:
$_POST['username'] and $_POST['email'] fetch the values from the form fields.
Empty Check:
empty($username) and empty($email) check if the form fields are empty. If they are, it prints a message indicating that the fields are required.
Example 3: Handling Multiple Fields with Both isset() and empty()
Form HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP Code (process.php):
<?php
// Step 1: Check if the form was submitted
if (isset($_POST['submit'])) {
// Step 2: Retrieve the form data
$username = $_POST['username'];
$email = $_POST['email'];
// Step 3: Validate the fields
if (empty($username) || empty($email)) {
echo "Both username and email are required.";
} else {
echo "Username: $username<br>";
echo "Email: $email<br>";
}
}
?>
Code Explanation:
Form Submission Check:
isset($_POST['submit']) ensures the form was submitted.
Retrieve Data:
$_POST['username'] and $_POST['email'] get the values from the form fields.
Validation:
empty($username) || empty($email) checks if either field is empty and provides a message if any are missing. If both are filled, it displays the values.
Example 4: Setting Default Values with empty()
Form HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Code (process.php):
<?php
// Step 1: Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Step 2: Retrieve the form data with default values
$username = !empty($_POST['username']) ? $_POST['username'] : 'Guest';
$email = !empty($_POST['email']) ? $_POST['email'] : 'No email provided';
// Step 3: Display the form data
echo "Username: $username<br>";
echo "Email: $email<br>";
}
?>
Code Explanation:
Form Submission Check:
$_SERVER["REQUEST_METHOD"] == "POST" ensures the form was submitted via POST.
Retrieve Data with Defaults:
Uses !empty($_POST['username']) ? $_POST['username'] : 'Guest' to provide default values if the form fields are empty.
Display Data:
Outputs the values of $username and $email, with defaults if fields are empty.
Example 5: Form Validation with Error Messages
Form HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Code (process.php):
<?php
// Step 1: Initialize error array
$errors = array();
// Step 2: Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Step 3: Retrieve the form data
$username = $_POST['username'];
$email = $_POST['email'];
// Step 4: Validate the form fields
if (empty($username)) {
$errors[] = "Username is required.";
}
if (empty($email)) {
$errors[] = "Email is required.";
}
// Step 5: Display errors or form data
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p>$error</p>";
}
} else {
echo "Username: $username<br>";
echo "Email: $email<br>";
}
}
?>
Code Explanation:
Initialize Errors:
Creates an empty array $errors to store validation messages.
Form Submission Check:
Ensures the form was submitted using POST.
Retrieve Data:
Gets the values from the form fields.
Validation:
Uses empty() to check for empty fields and adds messages to the $errors array.
Display Errors or Data:
Displays any error messages or, if no errors, shows the form data.
These examples illustrate how to use isset() and empty() to manage form submissions effectively, providing checks and handling for various scenarios in a beginner-friendly manner.