我有这个html
<select name="country">
<option value="Iraq">1</option>
<option value="Texas">2</option>
<option value="Paris">3</option>
...
<option value="n">nnn</option>
</select>
这个select元素中有很多选项,我真的不想允许人们更改任何选项的值,我无法阻止他们这样做,不过,我很好奇,有没有一种有效的PHP方法来检查值是否合法,例如,我可以这样做:
<?php
$country = $_POST['country'];
if(($country == "Iraq") && ($country == "Texas") && ($country == "Paris) ....($country == "n"))
{
allow stuff;
}
?>
但这需要大量的if语句,难道没有其他神奇的方法来解决这个问题吗?
当然,使用in_array
:
$countries = ['Iraq','Texas',...];
if(in_array($_POST['country'], $countries)) {
// allow stuff
}
构建一次$countries
数组,然后使用它生成<select
>HTML代码并验证提交。奖金
附带说明:我需要访问得克萨斯州。没意识到他们退出了!
这远非魔术,但一种(稍微有效的)检查方法是使用in_array
http://php.net/manual/en/function.in-array.php
一旦你有了一个国家的数组,你也可以使用它来生成下拉列表。