gpt4 book ai didi

PHP 验证一堆复选框失败

转载 作者:行者123 更新时间:2023-12-02 21:29:30 25 4
gpt4 key购买 nike

表单

echo '<form action="formProcess.php" method="post">';
echo '<input type="checkbox" name="country[]" value="US">';
echo '<input type="checkbox" name="country[]" value="UK">';
echo '<input type="checkbox" name="country[]" value="SE">';
echo '<input type="checkbox" name="country[]" value="CA">';
echo '<input type="submit" name="Submit" value="Submit">';
echo '</form>';

?>

formProcess.php

<?php


if (isset($_POST['country'])) {
echo 'Set <br>';
if (check($_POST['country'])){
echo 'Country OK<br>';
} else {
echo 'Country Faulty<br>';
}

} else {
echo 'Not Set';
}

function check($colors) { // This function is where I fail
global $countries;

foreach($colors as $country) {
echo "You selected: $country <br>";
if (array_key_exists($country,$countries)) {
return true;
} else {
return false;
}
}
}
?>

我正在尝试验证一堆复选框,但函数内的 return 部分出错了。

问题是,即使我选择多个复选框,我也只能输出一个值。问题出在函数的return 中。这是如何正确完成的?

输出

Set

You selected: US // Outputs only one even when more are selected.

Country OK

国家数组

$countries = array (
"US" => "United States Of America",
"GB" => "United Kingdom",
"CA" => "Canada"
// a lot more removed for this question
}

最佳答案

您可以使用选定的复选框创建一个数组并返回该数组。

function check($colors) { 
global $countries;
$checkedCountries = array();
foreach($colors as $country) {
echo "You selected: $country <br>";
if (array_key_exists($country,$countries)) {
$checkedCountries[] = $country;
echo $country . "<br />";
}
}
if(count($checkedCountries) > 0)
return true;
else
return false;
}

关于PHP 验证一堆复选框失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22666447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com