Page 1 of 1

How do I count backwards in a FOR loop?

Posted: Mon Oct 09, 2006 3:11 pm
by impulse()
I have this so far

Code: Select all

for ($i = count($_SESSION['requests']); $i = 0; $i--) {
  echo $_SESSION['requests'][$i], "<br>";
  }
But it doesn't do what it says on the tin.

Regards,

Re: How do I count backwards in a FOR loop?

Posted: Mon Oct 09, 2006 3:18 pm
by alex.barylski
Although possible, I can't see in this example why you would want too?? It's sometimes nessecary, like when implementing a tokenizer maybe, but for simple iterations it's best to go with what makes more sense...we count better forward much better than backwards...

Code: Select all

$cnt = count($_SESSION['requests']) - 1;
for($i=$cnt; $i>=0; $i--)
  // ... code here

Re: How do I count backwards in a FOR loop?

Posted: Mon Oct 09, 2006 3:27 pm
by Luke

Code: Select all

$backwards = array_reverse($_SESSION['requests']);
foreach ($backwards as $request) {
  echo $request, "<br>";
}

Re: How do I count backwards in a FOR loop?

Posted: Mon Oct 09, 2006 3:30 pm
by volka
The Ninja Space Goat wrote:

Code: Select all

$backwards = strrev($_SESSION['requests']);
foreach ($backwards as $request) {
  echo $request, "<br>";
}
:?:

Posted: Mon Oct 09, 2006 3:33 pm
by Luke
oops... I fixed it volka :oops:

Posted: Mon Oct 09, 2006 3:33 pm
by Jenk
rsort() for an alternative :)

Posted: Mon Oct 09, 2006 4:29 pm
by Ollie Saunders
Let me amplify the problem for everyone :)
for ($i = count($_SESSION['requests']); $i = 0;$i--)