dtueufe82643 2018-02-06 01:17
浏览 29
已采纳

如何检查数组中的变量是否介于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 2018-02-06 01:58
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化