Jump to content

looping reverse


9three

Recommended Posts

Hey,

 

I have a variable that holds an integer. I would like to get the values before that value but I'm having an issue.

 

$current = 7;

for($x = $current - 1; $x <= $current - 1 && $x > 0; --$x)
  echo $x;

 

Output is: 654321

 

What I need is 123456.

 

My eyes hurt, can someone help? :)

Link to comment
Share on other sites

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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.