如何测试 php 中的变量是否已设置
How to test if variable in php isset
我有一个包含姓名、收音机和电子邮件的表格。
<form action="index.php" method="POST" role="form">
<input class="form-control" name="name" type="text" placeholder="NAME">
<input class="form-control" name="email" type="text" placeholder="EMAIL(optional)">
<input type="radio" class="form-check-input" name="gender" value="male">Male
<input type="radio" class="form-check-input" name="gender" value="female">Female
<input type="radio" class="form-check-input" name="gender" value="other">Other
...
为了测试是否填写了姓名,电子邮件或收音机,我使用isset
if (isset($_POST['name'])) {
echo 'name isset';
}
if (isset($_POST['email'])) {
echo 'email isset';
}
if (isset($_POST['gender'])) {
echo 'gender isset';
}
我不明白的是:即使我将字段留空,它也会输出来自 name
和 email
循环的 2 个回声,而不是 gender
循环。
有人能解释一下为什么即使我将字段留空并提交,姓名和电子邮件的 return 值仍然为真吗?
为什么,如果我不点击任何收音机,这个 return 值是假的? (echo 'gender isset';
没有输出!)
因为如果您将字段留空,它们会向服务器发送一个空字符串。意思是 $_POST['name']
将包含空字符串 ''
函数 isset
检查值是否存在并且与 null
不同。在您的情况下,空字符串不同于 null
并且存在。
您可以改用 empty
,它会起作用。
例如:
if (!empty($_POST['name'])) {
echo 'name isset';
}
至于无线电 - 如果选择 none,则不会发送它们。这就是 isset
在那里工作的原因。
我有一个包含姓名、收音机和电子邮件的表格。
<form action="index.php" method="POST" role="form">
<input class="form-control" name="name" type="text" placeholder="NAME">
<input class="form-control" name="email" type="text" placeholder="EMAIL(optional)">
<input type="radio" class="form-check-input" name="gender" value="male">Male
<input type="radio" class="form-check-input" name="gender" value="female">Female
<input type="radio" class="form-check-input" name="gender" value="other">Other
...
为了测试是否填写了姓名,电子邮件或收音机,我使用isset
if (isset($_POST['name'])) {
echo 'name isset';
}
if (isset($_POST['email'])) {
echo 'email isset';
}
if (isset($_POST['gender'])) {
echo 'gender isset';
}
我不明白的是:即使我将字段留空,它也会输出来自 name
和 email
循环的 2 个回声,而不是 gender
循环。
有人能解释一下为什么即使我将字段留空并提交,姓名和电子邮件的 return 值仍然为真吗?
为什么,如果我不点击任何收音机,这个 return 值是假的? (echo 'gender isset';
没有输出!)
因为如果您将字段留空,它们会向服务器发送一个空字符串。意思是 $_POST['name']
将包含空字符串 ''
函数 isset
检查值是否存在并且与 null
不同。在您的情况下,空字符串不同于 null
并且存在。
您可以改用 empty
,它会起作用。
例如:
if (!empty($_POST['name'])) {
echo 'name isset';
}
至于无线电 - 如果选择 none,则不会发送它们。这就是 isset
在那里工作的原因。