[英]How to check if variables from the array are between the range of 0 and 101? php
I am trying to run a function which would show me if the variables in the array are between 0 and 101, but I can't find the right answer It always lets me to enter any number. 我正在尝试运行一个函数,该函数将向我显示数组中的变量是否在0到101之间,但是我找不到正确的答案。它总是让我输入任何数字。 Any ideas?`
有什么想法吗?
<?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";
}
The problem with your code example is the &&
("and") and ||
您的代码示例的问题是
&&
(“ and”)和||
("or") operator precedence in your conditional. (“或”)运算符的优先级。
Read in more human terms, your conditional looks like this: 用更人性化的术语阅读,您的条件如下:
IF #1 > 0 and #1 < 101
OR
#2 > 0 and #2 < 101
OR
...
So, as soon as ANY of your numbers are between 0 and 101, your conditional will be "truthy", and will continue to run array_sum()
. 因此,只要您的任何数字在0到101之间,您的条件将是“真实的”,并将继续运行
array_sum()
。
If you want to make sure ALL numbers pass your validation, you should use &&
instead of ||
如果要确保所有数字都通过验证,则应使用
&&
而不是||
. 。
You should look into foreach()
this way you can have an unlimited number of inputs too ! 您应该以这种方式查看
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
}
You will need to tailor it to your liking but it should get you going. 您将需要根据自己的喜好对其进行调整,但是它应该可以助您一臂之力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.