如何解决如何检查 HTML 表单中是否有多个值 isset()
我一直试图在网上找到如何做到这一点,但我找不到。 我有以下几点:
if (isset($_GET['the_country']))
我有一个 html 形式的选择框,用于“the_country”和“the_city”。如果设置了 the_country,设置了 the_city,以及设置了 the_country 和 the_city,我想有一个 if 语句。如果我希望它们像这样运行,我将如何读取 if 语句。我看到问题出现在哪里,即使两者都设置了,也需要我的第一个 if 语句,因为它们每个都是自己设置的。我将如何基本上将其转换为以下内容:
如果(the_country 已设置,而 the_city 未设置) 如果(the_city 已设置,而 the_country 未设置) If(the_country 已设置,the_city 已设置)
解决方法
根据当前的输入结构,可以将条件分为4块:
$isCountry = isset($_GET['the_country']);
$isCity = isset($_GET['the_city']);
if ($isCountry && $isCity) {
// both set
} elseif ($isCountry && !$isCity) {
// only country set
} elseif (!$isCountry && $isCity) {
// only city set
} else {
// none set
}
,
方法一:
它可以通过多种方式完成。但更直接的方法是直接编写 if-else。
if (isset($_GET['the_country']) && if (isset($_GET['the_city'])) {
// both the country and the city are set
} else if (isset($_GET['the_country']) && !isset($_GET['the_city'])) {
// country is set city is not set
} else if (!isset($_GET['the_country']) && isset($_GET['the_city'])) {
// country is not set the city is set
} else {
// both country and city are not set
}
isset
检查变量是否已设置。即使变量被赋值为空值,它也会返回 true。
<?php
$a='';
var_dump(isset($a));// true
var_dump(isset($b));// false
如果您需要检查 the_city
和 the_country
是否具有有效输入,请使用 empty()
而不是 isset()
。
方法 2:
显然,随着输入数量的增加,它会变得更加复杂。您的代码中会有一个很长的 if-else-if
阶梯。
为避免这种情况,您可以编写如下所示的验证逻辑:
$inputFields = [
'the_city' => null,'the_country' => null,];
$userInput = array_merge($inputFields,$_GET);
$validated = array_filter($userInput,function($val) {
return $val !== null;
});
$errors = array_diff_key($userInput,$validated);
if (! empty($errors)) {
echo 'The fields ' . implode(',',array_keys($errors)) . ' are empty';
}
此外,您可以考虑编写具有相同逻辑的验证类以进行代码重用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。