<?php
foreach(range(0,5) as $i) echo $i; // 012345
// but unlike python you also can range letters
foreach(range('a','z') as $l) echo $l; //abcdefghijklmnopqrstuvwxyz
// or floating
foreach(range(0.1, 0.2, 0.01) as $f) echo "$f; "; //0.1; 0.11; 0.12; 0.13; 0.14; 0.15; 0.16; 0.17; 0.18; 0.19; 0.2;
// negative step work with letters
foreach(range('z','a',-1) as $l) echo $l; // zyxwvutsrqponmlkjihgfedcba
// and dont stuck if invalid negative step just ignore and use abs(step) value
foreach(range(1,10,-2) as $i) echo $i; // 13579
// but throw fatal if step exceed the specified range, so, test if step in range before using
foreach(range(1,10,-20) as $i) echo $i;
// Fatal error: Uncaught ValueError: range(): Argument #3 ($step) must not exceed the specified range in /home/user/scripts/code.php:12
// Stack trace:
// #0 /home/user/scripts/code.php(12): range(1, 10, -20)
// #1 {main}
// thrown in /home/user/scripts/code.php on line 12
7条答案
按热度按时间iqjalb3h1#
直接来自docs:
ippsafx72#
老式
for
循环:或者使用range function:
ufj5ltwl3#
php里面有一个range函数,你可以这样使用。
但是不像python,你必须传递2个参数,range(10)将不起作用。
8xiog9wr4#
试试这个:
a2mppw5e5#
for ($i = 0; $i < LENGTH_GOES_HERE; $i++) { ... }
或
foreach (range(0, LENGTH_GOES_HERE - 1) as $i) { ... }
,参见range()。gijlo24d6#
这是一个python兼容的范围生成器
注解
j5fpnvbx7#