Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse order of foreach list items

Tags:

php

I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.

<?php     $j=1;          foreach ( $skills_nav as $skill ) {         $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';         $a .= $skill->name;                          $a .= '</a></li>';         echo $a;         echo "\n";         $j++;     } ?>   
like image 502
blkedy Avatar asked May 27 '12 22:05

blkedy


People also ask

How to iterate backwards through a list c#?

An alternative way to iterate backwards in a list is to reverse the list with the List. Reverse() method and iterate over the reversed list using the foreach statement. Note that this approach is not recommended as it changes the original order of the list. That's all about iterating backwards in a List in C#.

How do you reverse forEach in Java?

Since there does not exist a "last" element, it is mathematically impossible to reverse the order.


Video Answer


1 Answers

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(   '@jonathansampson',   '@f12devtools',   '@ieanswers' );  $index = count($accounts);  while($index) {   echo sprintf("<li>%s</li>", $accounts[--$index]); } 

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

Reversing the Array

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(   '@jonathansampson',   '@f12devtools',   '@ieanswers' );  foreach ( array_reverse($accounts) as $account ) {   echo sprintf("<li>%s</li>", $account); } 
like image 134
Sampson Avatar answered Sep 19 '22 16:09

Sampson