Zsolt Janes Zsolt Janes - 1 month ago 5
PHP Question

PHP multiple value for loop

I have the following php for loop

$screen = 1.3; // it can be other decimal value
for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
echo $i . ' - ' . $k . '<br>';
}


It works fine but i would like to run the for loop til 1.3 - 75 now it print me 1.2 - 50. I try to change $i <= $screen to $i = $screen but it does not work.

Answer

If you read http://php.net/manual/en/language.types.float.php there's a nice statement you should keep in mind:

Testing floating point values for equality is problematic, due to the way that they are represented internally

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

Based on the recommendation there you need to do something like :

<?php
$screen = 1.3; // it can be other decimal value
$epsilon=0.0001;
for ($i = 1, $k = 0; $i <= $screen+$epsilon; $i += 0.1, $k+=25) {
    echo $i . ' - ' . $k . "\n";
}