tags:

views:

125

answers:

5

In python we have:

for i in range(length)

What about in PHP?

+1  A: 

for ($i = 0; $i < LENGTH_GOES_HERE; $i++) { ... }

or

foreach (range(0, LENGTH_GOES_HERE - 1) as $i) { ... }, cf. range().

jensgram
the `foreach` line should use `LENGTH_GOES_HERE - 1`
intgr
@intgr I'm offsetting on the `low` instead.
jensgram
@intgr But you're right, I see. We want `$i` to have the same values as in the question :)
jensgram
+6  A: 

Straight from the docs:

foreach (range(0, 12) as $number) {
    echo $number;
}
int3
One caveat: Python's `range(0, 13)` or `range(13)` is equivalent to PHP's `range(0, 12)`
intgr
+1  A: 

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.

S.Mark
+1  A: 

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;
}
John Feminella
+3  A: 

Old fashioned for loops:

for ($i = 0; $i < length; $i++) {
    // ...
}

Or foreach using the range function:

foreach (range(1, 10) as $i) {
    // ...
}
Mikael S