Jump to content

looping reverse


9three

Recommended Posts

You are thinking all backwards. You want the values FROM one and UP TO your defined boundary, just do:

 

for ($x = 1; $x < $current; $x++) {
    echo $x;
}

 

So you loop from 1 up to one less than your $current value (that's why you use '<' instead of '<='). That should output 123456 if $current is 7.

Link to comment
https://forums.phpfreaks.com/topic/190062-looping-reverse/#findComment-1002758
Share on other sites

I see now what you are attempting; getting the previous five integers.

 

for ($x = $current-5; $x < $current; $x++) {
    if ($x < 1) {
        $x = 1;
    }
    echo $x;
}

 

That will give you the previous 5 integers before $current. Note the if() which is important if $current is lower than 5.

 

Cheers.

Link to comment
https://forums.phpfreaks.com/topic/190062-looping-reverse/#findComment-1002769
Share on other sites

Ok I figured it out with the code you guys provided.

 

Here is what I did. Any recommended improvement is always accepted :)

 

$current = 16;
if ($current <= 5) {
  for($i = 1;$i < $current; $i++) {
    echo $i.' ';
  }
}
else {
  for($i = $current - 5;$i <= $current - 1 && $i > 0; $i++) {
    echo $i.' ';
  }
}
echo ' Current:'.$current;

Link to comment
https://forums.phpfreaks.com/topic/190062-looping-reverse/#findComment-1002815
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.