I'm working on expanding my PHP skills and I'm trying to write a simple program that calculates volume and checks to make sure all the numerical values are from 0-20, but for some reason I can't get my program to recognize incorrect numbers.
<?php
//read deep end
$deepEnd = $_POST['deepEnd'];
//read shallow end
$shallowEnd = $_POST['shallowEnd'];
//read length
$length = $_POST['length'];
//read width
$width = $_POST['width'];
$flag = false;
$min = 0;
$max = 20;
if($deepEnd < $min && $deepEnd > $max){
$flag = true;
}
if($shallowEnd < $min && $shallowEnd > $max){
$flag = true;
}
if($length < $min && $length > $max){
$flag = true;
}
if($width < $min && $width > $max){
$flag = true;
}
$volume = 0.5*($deepEnd+$shallowEnd)*$length*$width*7.5;
echo "<h2>Volume Calculator</h2>";
if($flag == 'true'){
echo "<p>Incorrect value input. Please enter 0-20.</p>
";
} else {
echo "<p>Your volume is: ".$volume." gallons.</p>
";
}
?>
My input is being taken from my HTML program. The <input type='number'>
so I'm confused why my if statements aren't interpreting it correctly.
You are comparing each variable if it is less than $min
and more than $max
. Unless your $min
is greater than $max
, your code wouldn't work.
Example:
$min = 0;
$max = 10;
$x = 5;
if ($x < $min && $x > $max) { // this will always evaluate as false
// won't execute here
}
To solve your problem, which is to check if the value is out of scope of the $min
or $max
, you should use the ||
operator.
Example:
$min = 0;
$max = 10;
$x = -5;
if ($x < $min || $x > $max) { // true
// do something
}
It seems to me your logic is wrong, in the first check:-
if($deepEnd < $min && $deepEnd > $max){
$flag = true;
}
this will only return error if the $deepend is less than the min and greater than the max which could never really happen, testing your code :-
if($deepEnd < $min OR $deepEnd > $max){
$flag = true;
}
worked for me