Take the 2-minute tour ×

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.

share|improve this question
This is a duplicate of stackoverflow.com/questions/5315539/… –  Alex Dec 9 '11 at 19:11

3 Answers 3

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. */
share|improve this answer
+1 for the link. –  Jon Dec 9 '11 at 19:11
thank you kind sir –  Kevin Lee Dec 9 '11 at 19:13

You could do this:

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

foreach($i = $max; $i > 0; $i--) {
    $key = $values[$i];
    // do something with the key
share|improve this answer
foreach(array_reverse($array, true) as $key=>$value)

The array_reverse function will reverse an array.

share|improve this answer
thank you sir jakx –  Kevin Lee Dec 9 '11 at 19:13

Your Answer


