如何检查数组中的变量是否介于0和101之间? PHP

如何检查数组中的变量是否介于0和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. 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"; 
      }

我正在尝试运行一个函数,它会告诉我数组中的变量是否在0到101之间,但是 我找不到合适的答案它总是让我输入任何数字。 有什么想法?` p>

 &lt;?php 
 
 $ n =数组($ _ POST [number1],$ _POST [number2],$ _POST [number3],$  _POST [number4],$ _POST [number5]); 
 
 
 if($ n [0]&lt; 101&amp;&amp; $ n [0]&gt; 0 || $ n [1]&lt; 101  &amp;&amp; $ n [1]&gt; 0 || $ n [2]&lt; 101&amp;&amp; $ n [2]&gt; 0 || $ n [3]&lt; 101&amp;&amp; $ n  [3]&gt; 0 || $ n [4]&lt; 101&amp;&amp; $ n [4]&gt; 0){
 echo array_sum($ n)/ 5;  
} else {
 echo“等级必须在1到100之间”;  
} 
  code>  pre> 
  div>

The problem with your code example is the && ("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().

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 !

$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.