[英]Is there something like for i in range(length) in PHP?
在python中,我們有:
for i in range(length)
在 PHP 中呢?
直接來自文檔:
foreach (range(0, 12) as $number) {
echo $number;
}
老式for
循環:
for ($i = 0; $i < length; $i++) {
// ...
}
或者使用范圍功能 :
foreach (range(1, 10) as $i) {
// ...
}
for ($i = 0; $i < LENGTH_GOES_HERE; $i++) { ... }
要么
foreach (range(0, LENGTH_GOES_HERE - 1) as $i) { ... }
,cf。 范圍() 。
php中有一個范圍函數,你可以這樣使用。
foreach( range(0,10) as $y){
//do something
}
但是與python不同,你必須傳遞2個參數,范圍(10)將不起作用。
嘗試這個:
// Generates the digits in base 10.
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
foreach (range(0, 9) as $number) {
echo $number;
}
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.