I banged my head up against the wall for a few hours on this problem. I thought I was comparing
variables of equal value in my script and it turned out that because I was comparing float
variables the chances of them ever being equal were close to none. The first block of code worked
great as long as I was incrementing $i by 1 in the for loop. It fell to pieces after I changed the
for loop to increment $i by .1
One solution was to subtract the two variables I was comparing and then test the result for being
less than a number that is close to zero. Another solution was to multiply the variables being
compared by 10 (or 100, 1000,...) so that the variables were both integers before comparison.
Hope this helps someone.
Code that DOES NOT work.
<?php
$start = 1;
$end = 3;
$target = 2;
for ($i=$start; $i<=$end; $i+=.1){
if ( $i === $target ){
echo ("<BR>$i - $target, Numbers are equal in value.");
} else {
echo ("<BR>$i - $target, Numbers are not equal in value.");
}
}
?>
Code that DOES work.
<?php
$start = 1;
$end = 3;
$target = 2;
for ($i=$start; $i<=$end; $i+=.1){
if(abs($i - $target) < .00001) {
echo ("<BR>$i - $target, Numbers are equal in value.");
} else {
echo ("<BR>$i - $target, Numbers are not equal in value.");
}
}
?>
More code that DOES work.
<?php
$start = 1;
$end = 3;
$target = 2;
for ($i=$start; $i<=$end; $i+=.1){
if ( ($i*10) === ($target*10) ){
echo ("<BR>$i - $target, Numbers are equal in value.");
} else {
echo ("<BR>$i - $target, Numbers are not equal in value.");
}
}
?>