Home >Backend Development >PHP Tutorial >`isset()` vs. `empty()`: When Should You Use Each for PHP Variable Evaluation?

`isset()` vs. `empty()`: When Should You Use Each for PHP Variable Evaluation?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 03:27:09627browse

`isset()` vs. `empty()`: When Should You Use Each for PHP Variable Evaluation?

isset() versus empty() for Variable Evaluation

In coding, it is often necessary to assess whether a variable is set or empty. While similar in functionality, the choices between isset() and empty() vary depending on the desired result.

empty()

empty() checks if a variable is set and simultaneously examines its value. It considers variables with the following values as empty:

  • "" (empty string)
  • 0 (integer)
  • 0.0 (float)
  • "0" (string)
  • NULL
  • FALSE
  • array() (empty array)
  • Undeclared variables

isset()

isset(), on the other hand, solely determines if a variable has been set and is not NULL. It does not consider the variable's value.

Which to Use

The choice between isset() and empty() depends on the desired behavior:

  • To check if a variable is both set and not empty (with the exception of NULL), use empty().
  • To check if a variable is set, regardless of its value, use isset().

Example

Here's an improved version of the code example provided:

<?php
    $var = '23';
    
    if (!empty($var)) {
        echo 'not empty';
    } else {
        echo 'is not set or empty';
    }
?>

This revised code uses empty() directly without the need for isset() since empty() checks for both the existence and non-empty value of the variable.

The above is the detailed content of `isset()` vs. `empty()`: When Should You Use Each for PHP Variable Evaluation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn