3

How do I set my foreach loop to start looking at the last entry of the array then each loop will go backwards instead of forward?

Thank you.

1

3 Answers 3

10

You could just reverse the array:

$reverse = array_reverse($array, true); // true to preserve keys
foreach($reverse as $key => $value) { /* etc. */ }

Or if you're sure that the array contains only numeric keys, this is probably faster:

for($i = count($array) - 1; $i >= 0; $i--) {
  /* etc. */
}
Sign up to request clarification or add additional context in comments.

Comments

1
foreach(array_reverse($array, true) as $key=>$value)

The array_reverse function will reverse an array.

Comments

1

You could do this:

$values = array();
$max = count($values);

foreach($i = $max; $i > 0; $i--) {
    $key = $values[$i];
    // do something with the key
}

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.