Lots of PHP for the 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 start the for til 1.3 - 75 loop, now it prints me from 1.2 to 50. I am trying to change the screen of $ i <= $ to $ i = $, but this will not work.

+5
source share
3 answers

If you read http://php.net/manual/en/language.types.float.php , you should keep in mind a good statement:

Testing floating point values ​​for equality is problematic because they are represented internally.

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

Based on the recommendation, 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"; } 
+5
source

Two solutions:

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

OR

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

Tested. Both work ... as far as I understand what you want to do.

Tested output of both:

 1 - 0 1.1 - 25 1.2 - 50 1.3 - 75 
+2
source

You got your answer that another way to do the same is to do so. A source

 $start = 1; $end = 1.3; $place = 1; $step = 1 / pow(10, $place); for($i = $start, $k=0; $i <= $end; $i = round($i + $step, $place), $k += 25) { echo $i . ' - ' . $k . '<br>'; } 
0
source

Source: https://habr.com/ru/post/1258535/


All Articles