How do I count backwards in a FOR loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
impulse()
Forum Regular
Posts: 748
Joined: Wed Aug 09, 2006 8:36 am
Location: Staffordshire, UK
Contact:

How do I count backwards in a FOR loop?

Post 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,
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

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

Post 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
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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

Post by Luke »

Code: Select all

$backwards = array_reverse($_SESSION['requests']);
foreach ($backwards as $request) {
  echo $request, "<br>";
}
Last edited by Luke on Mon Oct 09, 2006 3:32 pm, edited 1 time in total.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

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

Post by volka »

The Ninja Space Goat wrote:

Code: Select all

$backwards = strrev($_SESSION['requests']);
foreach ($backwards as $request) {
  echo $request, "<br>";
}
:?:
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

oops... I fixed it volka :oops:
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

rsort() for an alternative :)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Let me amplify the problem for everyone :)
for ($i = count($_SESSION['requests']); $i = 0;$i--)
Post Reply