PHP中是否有类似于for i in range(length)的写法?
在Python中,我们有:
for i in range(length)
那在PHP中呢?
7 个回答
2
这是一个符合Python标准的范围生成器
foreach ($x in xrange(10)) {
echo "$x ";
} // expect result: 0 1 2 3 4 5 6 7 8 9
function xrange($start, $limit = null, $step = null) {
if ($limit === null) {
$limit = $start;
$start = 0;
}
$step = $step ?? 1;
if ($start <= $limit) {
for ($i = $start; $i < $limit; $i += $step)
yield $i;
} else
if ($step < 0)
for ($i = $start; $i > $limit; $i += $step)
yield $i;
}
大部分内容来自 https://www.php.net/manual/en/language.generators.overview.php
注意事项
- 它不会自动向后计数(像Python那样,而不是PHP)
- 它可以接受1、2或3个参数(像Python)
- 它会计算到$limit - 1(像Python,而不是PHP)
- 如果你的参数不合理,就不会有结果(像Python)
- 它不会把范围存储在内存中(不像PHP),所以你可以有非常大的范围
5
老式的 for
循环:
for ($i = 0; $i < length; $i++) {
// ...
}
或者使用 range 函数 的 foreach 循环:
foreach (range(1, 10) as $i) {
// ...
}
12
直接来自文档:
foreach (range(0, 12) as $number) {
echo $number;
}