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";
}
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.