English 中文(简体)
Is there something like for i in range(length) in PHP?
原标题:

In python we have:

for i in range(length)

What about in PHP?

最佳回答

Straight from the docs:

foreach (range(0, 12) as $number) {
    echo $number;
}
问题回答

Old fashioned for loops:

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

Or foreach using the range function:

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

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.

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;
}

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

or

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

Here s a python compliant range generator


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

Notes

  • It will not automatically step backwards (like python, unliike PHP)
  • It can accept 1, 2 or 3 arguments (like python)
  • It will count to $limit - 1 (like python, unlike PHP)
  • If your arguments are silly, you get no results (like python)
  • It doesn t store the range in memory (unlike PHP) so you can have HUGE ranges
<?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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签