我正在尝试运行一个函数,它会告诉我数组中的变量是否在0到101之间,但我找不到正确的答案它总是让我输入任何数字。有什么想法吗?`
<?php
$n = array($_POST[number1], $_POST[number2], $_POST[number3], $_POST[number4], $_POST[number5]);
if ($n[0] < 101 && $n[0] >0 || $n[1] < 101 && $n[1] >0 || $n[2] < 101 && $n[2] >0 || $n[3] < 101 && $n[3] >0 || $n[4] < 101 && $n[4] >0){
echo array_sum($n) / 5;
} else {
echo "The grade must be between 1 and 100";
}
答案 0 :(得分:1)
您的代码示例的问题是条件中的&&
(“和”)和||
(“或”)运算符优先级。
阅读更多人性化术语,您的条件如下:
IF #1 > 0 and #1 < 101
OR
#2 > 0 and #2 < 101
OR
...
因此,只要您的任何数字在0到101之间,您的条件就会“真实”,并且会继续运行array_sum()
。
如果您想确保所有数字都通过验证,则应使用&&
代替||
。
答案 1 :(得分:0)
你应该以这种方式调查foreach()
,你也可以拥有无限数量的输入!
$inputValid = 0;
foreach ($n as $key => $value) {
if($value > 0 AND $value < 101){
$inputValid++;
}else{
echo 'The grade must be between 1 and 100';// could use $key show which gives the error
}
}
if(count($n)!=$inputValid){
//error and/or global message
}else{
//proceed
}
你需要根据自己的喜好定制它,但它应该让你去。