"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > When Should I Use `isset()` and `!empty()`?

When Should I Use `isset()` and `!empty()`?

Posted on 2025-03-23
Browse:697

When Should I Use `isset()` and `!empty()`?

In Which Instances Should I Utilize isset() and !empty()

The isset() function, as its name suggests, checks the existence of a variable. It evaluates to TRUE if the variable has any value assigned to it, including an empty string, the boolean value FALSE, or the integer 0. However, it returns FALSE for variables that are explicitly set to NULL.

On the other hand, the !empty() function reverses the logic of isset(). It returns FALSE if the variable is set and has a non-empty, non-zero value, and TRUE otherwise.

When to Use isset()

isset() is useful when verifying the declaration and existence of a variable, especially when dealing with variables that may come from external sources such as forms or configuration files. It can provide insight into whether the variable was set intentionally or was inadvertently omitted.

For example, if you have an HTML form with an optional checkbox, you can use isset() to check if the checkbox was checked before processing its value.

if (isset($_POST['optional_checkbox']) && $_POST['optional_checkbox'] == 'on') {
    // Checkbox was checked
}

When to Use !empty()

!empty() is appropriate when you need to validate input that should not be empty. It ensures that the input has a non-empty value, which could be a non-zero number, a non-empty string, or a non-empty array.

For instance, if you are building a form that collects user addresses, you can use !empty() to check if the address field is filled in to prevent empty submissions.

if (!empty($_POST['address'])) {
    // Address field is not empty
    // Validate address and save
} else {
    // Address field is empty
    // Display error message
}

In summary, isset() checks for the existence of a variable, while !empty() checks for a non-empty value. While isset() is often used for verifying variable declaration, !empty() is preferred for validating user input to ensure non-empty values.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3