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.

Kevin Lee
  • 1,079
  • 6
  • 17
  • 34
  • This is a duplicate of http://stackoverflow.com/questions/5315539/iterate-in-reverse-through-an-array-with-php-spl-solution – Alex Dec 09 '11 at 19:11

3 Answers3

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. */
}
goto-bus-stop
  • 11,655
  • 2
  • 24
  • 31
1
foreach(array_reverse($array, true) as $key=>$value)

The array_reverse function will reverse an array.

jakx
  • 748
  • 5
  • 8
1

You could do this:

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

foreach($i = $max; $i > 0; $i--) {
    $key = $values[$i];
    // do something with the key
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
Naterade
  • 2,635
  • 8
  • 34
  • 54