5

Say i start my counter at 400. How would i execute a foreach loop that will run backwards until 0?

pseudocode

$i = 400;
foreach(**SOMETHING**)){
//do stuff
$i--;
}
2
  • Actualy you answered a question with complex code there is also a for loop. You didnt decrement it but incrementig it everyone should look at it stackoverflow.com/questions/1656731/… This question is in my opinion spam and should be flagged Commented Jan 18, 2010 at 21:44
  • The question was how to do it with foreach, which is hard enough to do for most people as most answers show. Commented Jan 18, 2010 at 22:39

4 Answers 4

23
for($i = 400; $i > 0; $i--)
{
  // do stuff
}

other ways to do it:

$i = 400;

while($i > 0)
{
  // do stuff
  $i--;
}

or

$a = range(400, 1);

foreach($a as $i)
{
  // do stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

The decrementing while is very nice.
6

In case you really want to iterate backwards over an existing array you can use array_reverse():

foreach(array_reverse($myArray) as $myArrayElement){
  // do stuff with $myArrayElement
}

Comments

4

how about a for loop

for($i = 400; $i > 0; $i--)
{
    //stuff
}

Comments

1

foreach is used for iterating over sequences or iterators. If you need a conditional loop then use for or while.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.