4

Could it be possible to use the range() function in PHP to generate a list of fractions or decimals?

2 Answers 2

8

Yeah, if you specify the step (third parameter). This parameter is only available in PHP 5, but you should be using that by now anyway.

For example, to generate decimals between 0 and 1, inclusive, in intervals of 0.1:

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

Output:

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

It's broken for me now on PHP 7.0.10, probably due to rounding issues depending on the 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
)

Bit it is broken for the range 0.2..0.9, for instance (0.9 is missing):

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.