Reputation: 34207
In python we have:
for i in range(length)
What about in PHP?
Upvotes: 10
Views: 5230
Reputation: 11
<?php
// using native php function range(start, end, step=1): array
// examples
foreach(range(0,5) as $i) echo $i; // will show 012345
// but unlike python in php you also can range letters
foreach(range('a','z') as $l) echo $l;
// will show abcdefghijklmnopqrstuvwxyz
// or in php can range floating
foreach(range(0.1, 0.2, 0.01) as $f) echo "$f; ";
// will show 0.1; 0.11; 0.12; 0.13; 0.14; 0.15; 0.16; 0.17; 0.18; 0.19; 0.2;
// or also php can do negative step work with letters
foreach(range('z','a',-1) as $l) echo $l;
// will show zyxwvutsrqponmlkjihgfedcba
// and php dont stuck or crash if invalid negative step
// php just ignore negtive step and use abs(step) value
foreach(range(1,10,-2) as $i) echo $i;
// will show 13579
// but throw fatal if step exceed the specified range
// so, need to test if step in range before using
foreach(range(1,10,-20) as $i) echo $i;
/* will throw 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
*/
?>
Upvotes: 0
Reputation: 13963
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;
}
mostly cribbed from https://www.php.net/manual/en/language.generators.overview.php
Upvotes: 2
Reputation: 31508
for ($i = 0; $i < LENGTH_GOES_HERE; $i++) { ... }
or
foreach (range(0, LENGTH_GOES_HERE - 1) as $i) { ... }
, cf. range().
Upvotes: 2
Reputation: 5198
Old fashioned for
loops:
for ($i = 0; $i < length; $i++) {
// ...
}
Or foreach using the range function:
foreach (range(1, 10) as $i) {
// ...
}
Upvotes: 5
Reputation: 311665
Try this:
// 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;
}
Upvotes: 1
Reputation: 123889
There is a range function in php, you can use like this.
foreach( range(0,10) as $y){
//do something
}
but unlike python, you have to pass 2 parameters, range(10) will not work.
Upvotes: 1