dtueufe82643
dtueufe82643
2018-02-06 01:17

如何检查数组中的变量是否介于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"; 
      }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzhang3482 dongzhang3482 3年前

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

    点赞 评论 复制链接分享
  • dongteng0748 dongteng0748 3年前

    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.

    点赞 评论 复制链接分享

相关推荐