PHP: Can range () be used for fractions?

Is it possible to use the range () function in PHP to create a list of fractions or decimals?

+3
source share
2 answers

Yes, if you specify a step (third parameter). This option is only available in PHP 5, but you should still use it.

For example, to create decimals between 0 and 1 inclusively at 0.1 intervals:

print_r(range(0, 1, 0.1));

Conclusion:

Array
(
    [0] => 0
    [1] => 0.1
    [2] => 0.2
    [3] => 0.3
    [4] => 0.4
    [5] => 0.5
    [6] => 0.6
    [7] => 0.7
    [8] => 0.8
    [9] => 0.9
    [10] => 1
)
+6
source

Now it crashed in PHP 7.0.10, probably due to rounding problems depending on range boundaries.

It works for the range 0.1..0.9:

print_r(range(0.1, 0.9, 0.1));
Array
(
    [0] => 0.1
    [1] => 0.2
    [2] => 0.3
    [3] => 0.4
    [4] => 0.5
    [5] => 0.6
    [6] => 0.7
    [7] => 0.8
    [8] => 0.9
)

The bit is divided into a range 0.2..0.9, for example ( 0.9missing):

print_r(range(0.2, 0.9, 0.1));
Array
(
    [0] => 0.2
    [1] => 0.3
    [2] => 0.4
    [3] => 0.5
    [4] => 0.6
    [5] => 0.7
    [6] => 0.8
)
0
source

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


All Articles