PHP 中的 isset() 与 empty() 函数

本文将介绍 PHP isset()empty() 函数。我们将介绍如何使用这些函数来执行以下操作。

  1. 检查变量是否被声明和设置。
  2. 检查变量是否不为空或 null
  3. 创建一个 PHP 验证表单。

让我们直接跳进去。

使用 isset() 函数检查 PHP 中是否设置了变量

isset() 函数检查是否设置了变量。当变量被声明并且不为空时,该函数返回 true

在下面的示例代码中,我们将使用 isset() 函数来检查是否设置了两个变量 $x$y

这是我们变量的值,$x = 0$y = null

例子:

<?php
$x = 0;
//Check if our variable is set and not null
if (isset($x)) {
  echo "The variable 'x' is set and not null.<br>";
}else{
  echo "The variable 'x' either null or not set.<br>";
}
$y = null;
//Check if our variable is set and not null
if (isset($y)) {
  echo "The variable 'y' is set and not null.<br>";
}else{
  echo "The variable 'y' is either null or not set.<br>";
}
?>

输出:

The variable 'x' is set and not null.
The variable 'y' is either null or not set.

正如预期的那样,$x 不为空,而 $y 已设置但为空。这取决于你希望如何回显结果。

你可以将函数与多个变量一起使用。但是,它仅在设置所有变量时才返回 true。

在 PHP 中使用 empty() 函数检查变量是否为空

empty() 函数检查变量是否已设置且不为空。

让我们看一个示例代码。

<?php
$x = 0;
//Check if our variable is empty
if (empty($x)) {
  echo "The variable 'x' is empty.<br>";
}else{
  echo "The variable 'x' is not empty.<br>";
}
$y = null;
//Check if our variable is empty
if (empty($y)) {
  echo "The variable 'y' is empty.<br>";
}else{
  echo "The variable 'y' is not empty.<br>";
}
?>

输出:

The variable 'x' is empty.
The variable 'y' is empty.

empty() 函数将以下内容视为空。

  1. 0
  2. 0,0
  3. Null
  4. False
  5. ""

在 PHP 中使用 isset()empty() 函数创建验证表单

我们将在下面的示例代码中的根目录中创建一个基本的 HTML 表单。我们将创建一个索引文件并将其保存在根目录的文件夹中。我们的索引文件会给用户一个警告。

例子:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Delftstack Tutorials</title>
</head>
<body>
<h2>Validation Form </h2>
<form action="index/index.php" method="get">// The form index.php is stored in the folder index
NAME: <input type="text" name="name" />
<br/>
E-Mail: <input type="text" name="email" />
<br/>
<input type="submit" value="validate" >
</form>
</body>
</html>

输出:

PHP 中的 isset() 与 empty() 函数

例子:

<?php
if (isset($_GET['name']) AND isset($_GET['email']))
{
$name=$_GET['name'];
$email=$_GET['email'];
}
else
{
die("Acces this file from the HTML page");
}
if(empty($name))
{
die("Enter a name");
}
else
{
if (is_numeric($name))
{
die("Name Must contain Alphabet Values");
}
else
{
echo "Name: $name <br /> Email: $email";
}
}
?>

形成我们的表单,让我们尝试验证以下内容。

  1. Joycelyn Lee, joycelynlee@delftstack.com
  2. 12567, 1234@gmail.com

输出 1:

PHP 中的 isset() 与 empty() 函数

输出 2:

PHP 中的 isset() 与 empty() 函数

PHP 中 isset()empty() 函数的区别

  1. isset() 函数检查变量是否已设置,而 empty() 函数检查变量是否已设置且不为空。
  2. isset() 函数将 0 视为变量,而 empty() 函数将 0 视为空。