Home  >  Article  >  Backend Development  >  What is the difference between null and empty in php

What is the difference between null and empty in php

WBOY
WBOYOriginal
2022-02-21 15:17:042744browse

The difference between null and empty in php: empty is a function used to check whether a variable is empty. If the variable is empty, it returns true; and null is a data type, indicating that a variable has no value and is empty. , when the variable is assigned a value of mull, is not assigned a value, or is unset(), it is expressed as null.

What is the difference between null and empty in php

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

What is the difference between null and empty in php

null means that a variable has no value. There are three situations when a variable is null:

1. It is assigned a value of NULL.

2. Has not been assigned a value.

3. By unset().

empty() function is used to check whether a variable is empty.

empty() Determines whether a variable is considered empty. When a variable does not exist, or its value is equal to FALSE, then it is considered not to exist. empty() does not generate a warning if the variable does not exist.

empty() After version 5.5, it supports expressions, not just variables.

Syntax

bool empty ( mixed $var )

Parameter description:

$var: Variable to be checked.

Note: Prior to PHP 5.5, empty() only supported variables; anything else would cause a parsing error. In other words, the following code will not work:

empty(trim($name))

Instead, you should use:

trim($name) == false

empty() and will not generate a warning, even if the variable does not exist. This means that empty() is essentially equivalent to !isset($var) || $var == false.

Returns FALSE when var exists and is a non-empty and non-zero value, otherwise returns TRUE.

The following variables will be considered empty:

  • "" (empty string)

  • 0 (as 0 as an integer)

  • 0.0 (0 as a floating point number)

  • "0" (0 as a string)

  • NULL

  • ##FALSE

  • ##array() (an empty array)
  • $var; (a variable declared but without a value)
  • Example
<?php
$ivar1=0;
$istr1=&#39;Runoob&#39;;
if (empty($ivar1))
{
    echo &#39;$ivar1&#39; . " 为空或为 0。" . PHP_EOL;
}
else
{
    echo &#39;$ivar1&#39; . " 不为空或不为 0。" . PHP_EOL;
}
if (empty($istr1))
{
    echo &#39;$istr1&#39; . " 为空或为 0。" . PHP_EOL;
}
else
{
    echo &#39;$istr1&#39; . " 字符串不为空或不为0。" . PHP_EOL;
}
?>

Recommended study: "

PHP Video Tutorial

The above is the detailed content of What is the difference between null and empty in php. 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