HOWTO · PHP

PHP 中的 isset() 與 empty() 函式

本文介紹 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>

輸出:

使用 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:

輸入驗證表單資訊

輸出 2:

驗證表的輸出

PHP 中 isset()empty() 函式的區別

  1. isset() 函式檢查變數是否已設定,而 empty() 函式檢查變數是否已設定且不為空。
  2. isset() 函式將 0 視為變數,而 empty() 函式將 0 視為空。