简体   繁体   中英

How can i make the for loop parameters dynamic

for ($i=40; $i>=30; $i--)  //code will display data for top x row
for ($i=1; $i<=9; $i++)    //code will display data for left y column
for ($i=29; $i>=21; $i--)  //code will display data for bottom x row
for ($i=30; $i>=39; $i++)  //code will display data for right y column

These 4 loops all do the same thing. In my index.php im using "include" to get the 4 loops that are in 4 different files. How can I make the for loop dynamic?

Algoritihm:

$i = (40,1,29,30)  <--will be any of those 4
$maxlow = (30,9,21,39) 
$check =(>,<)     <--value depends on whether $i > or < $maxlow
$icrement =  (--,++)   <-- if $check is > then decrease, otherwise increment

for ($i; $i($check)=$maxlow; $i($increment) <---what i am trying to do
// $step is either 1 (incrementing) or -1 (decrementing)
foreach (range($begin, $maxlow, $step) as $i) {

}
$low = [40,1,29,30](rand(0,3);
$high = [30,9,21,39](rand(0,3);
$modifier = ($low > $high) ? -1 : 1;

for($i = $low; ($i * $modifier) < ($high * $modifier); $i += $modifier)
{
  doStuff();
}

Settings for given loop:

$diff = -1;
$start = 40;
$stop = 30 + $diff;

The loop itself, always like this:

for ($i = $start; $i != $stop; $i += $diff)

why not just use for with switch inside, like this:

for ($i=1; $i >=39; $i++) {
    switch($i) {
       case ($i>=1 && $i<=9):
       break;
       ...
       ...
       case ($i>40):
       //do something
       break;
    }

}

It will be much more readable, and easier to understand/edit in future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM