Home >Backend Development >PHP Tutorial >How to Check Variable Undefinedness in PHP?

How to Check Variable Undefinedness in PHP?

DDD
DDDOriginal
2024-10-19 19:58:291088browse

How to Check Variable Undefinedness in PHP?

Determining Variable Undefinedness in PHP

In JavaScript, "document.createTouch !== undefined" checks for the undefinedness of "document.createTouch." Seeking an equivalent in PHP, let's explore ways to determine if a variable is undefined.

Using "isset()"

Unlike JavaScript, PHP does not have an explicit "undefined" keyword. Instead, you can use "isset()" to check if a variable has been defined. It returns true if the variable exists and false otherwise. For example:

<code class="php">$isTouch = isset($variable);</code>

Handling Special Cases

It's important to note that "isset()" returns true even if the variable contains the value NULL. To check if a variable is undefined and not just empty or set to NULL, you can use the following:

<code class="php">if (!isset($variable) || is_null($variable)) {
  // $variable is undefined
}</code>

Using "empty()"

Alternatively, you can use "empty()" to check if a variable is undefined or contains certain values, including the empty string, zero, NULL, and an empty array. However, "empty()" will not distinguish between undefined variables and those set to false.

<code class="php">$isTouch = empty($variable);</code>

The above is the detailed content of How to Check Variable Undefinedness 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