Compare PHP's isset(), empty() and is_null() functions
You will use variables in almost every program written in PHP. Most of the time these variables have a value, and we usually create them with an initial value. However, there's always a chance that some of the variables you use are uninitialized. This may cause PHP to issue warnings about the use of undefined variables.
There may be many reasons for undefined variables. The most common problem is that you don't actually define the variable, or you make a typo when reusing it somewhere else. This is just a programming error. However, another possibility that could result in an undefined variable is that it is conditionally defined.
You may also find that the value of a variable is NULL
. This can happen for a variety of reasons. For example, the variable may simply not have been initialized with a value. Or the function might return null to indicate some kind of error.
Regardless, using a variable before defining it or when it has a null value may have unintended consequences. In this tutorial, I will show you how to check if an element is defined and see if it is empty or null.
You can use isset()
, empty()
or is_null()
to check whether one or all of the conditions are true or false.
definition
Let's start with some definitions.
-
isset()
: You can useisset()
to determine whether a variable has been declared and is different fromnull
. -
empty()
: Used to determine whether the variable exists and the value of the variable is not equal tofalse
. -
is_null()
: This function is used to check whether the variable isnull
.
PHP isset()
and empty()
As we can see from the definition, if we previously defined the variable and set its value to something other than NULL
, isset()
will return true
. This can include 0
, the empty string, or false
. On the other hand, empty()
will return true
whenever a variable value is set to evaluate to false
— we call these "false" values. Examples of falsey values include 0
, the empty string ""
and the string "0"
, the empty array, NULL
, or of course is a boolean value false
.
isset()
and empty()
is that they are both language constructs and therefore cannot be called using variable functions.
The code snippet below should explain the difference between the two.
<?php $fruit = ''; if(isset($fruit)) { echo 'Do you like '.$fruit.'?'; } // Output: Do you like ? if(!empty($fruit)) { echo 'Do you like '.$fruit.'?'; } // No Output ?>
Please note that empty()
can be written using the isset()
function:
<?php function my_empty($x) { return !isset($x) || $x == false } ?>
Of course, it's usually easier to use the built-in empty()
function.
PHP isset()
and is_null()
If the value of the variable has been explicitly set to NULL
, the is_null()
function will return true
. Otherwise, it just returns false
. On the other hand, isset()
returns true
whenever a variable is defined and its value is not NULL
.
Here is a basic example to show the difference between them.
<?php $fruit = NULL; if(isset($fruit)) { echo 'Do you like '.$fruit.'?'; } // No Output if(is_null($fruit)) { echo 'There is no fruit.'; } // Output: There is no fruit. ?>
PHP empty()
and is_null()
If the value of the variable evaluates to false
, the empty()
function will return true
. This can mean an empty string, NULL
, an integer 0
, or an array with no elements. On the other hand, is_null()
will return true
only if the value of the variable is NULL
.
Here is a basic example to show the difference between them.
<?php $person = ['first_name' => 'Monty', 'last_name' => '', 'age' => '83', 'fav_movie' => NULL]; if(empty($person['last_name'])) { if(is_null($person['last_name'])) { echo 'The last name is set to NULL.'; } else { echo 'The last name is probably an empty string.'; } } // Output: The last name is probably an empty string. if(is_null($person['fav_movie'])) { echo $person['first_name'].' did not specify a favorite movie.'; } // Output: Monty did not specify a favorite movie.
IMPORTANT POINTS TO REMEMBER
There are two tips you can use to write cleaner code and avoid errors in the future.
1. Unlike empty()
and is_null()
, you can pass multiple values to isset()
at once to check whether Any are undefined or set to NULL
. In this case, isset()
will only return true
if none of the passed values are NULL
.
2. Do not use ==
to check if the value is NULL
. This will provide false positives for erroneous values such as the empty string that evaluates to false
.
Final Thoughts
This tutorial quickly explains the differences between isset()
, empty()
and is_null()
. Hopefully you'll now be able to determine which of these is best for you to use in your code.
The above is the detailed content of Compare PHP's isset(), empty() and is_null() functions. For more information, please follow other related articles on the PHP Chinese website!

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version