是否可以使用PHP中的range()函数生成分数或小数的列表?
答案 0 :(得分:7)
是的,如果指定步骤(第三个参数)。此参数仅在PHP 5中可用,但您现在应该使用它。
例如,以0.1:
的间隔生成0到1之间的小数,包括0和1print_r(range(0, 1, 0.1));
输出:
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
)
答案 1 :(得分:1)
现在在PHP 7.0.10上已经破解了,可能是由于舍入问题取决于范围边界。
适用于范围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
)
比特它在0.2..0.9
范围内被破坏,例如(0.9
缺失):
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
)