Possible to Iterate Backwards Through a Foreach

Possible to iterate backwards through a foreach?

When working with a list (direct indexing), you cannot do it as efficiently as using a for loop.

Edit: Which generally means, when you are able to use a for loop, it's likely the correct method for this task. Plus, for as much as foreach is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach for looping.

Iterate through a foreach loop backwards in PHP

if you don't have a date field in your table .. you can order by id in a Descending order

    $sql = "SELECT link FROM `UPLOADPICS` ORDER BY `id` DESC";

if you don't like that you can use array_reverse() function

Can one do a for each loop in java in reverse order?

The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list.

As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.

For example:

public class Reversed<T> implements Iterable<T> {
private final List<T> original;

public Reversed(List<T> original) {
this.original = original;
}

public Iterator<T> iterator() {
final ListIterator<T> i = original.listIterator(original.size());

return new Iterator<T>() {
public boolean hasNext() { return i.hasPrevious(); }
public T next() { return i.previous(); }
public void remove() { i.remove(); }
};
}

public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}

And you would use it like:

import static Reversed.reversed;

...

List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
doSomethingWith(s);
}

Reverse order of foreach list items

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);
}

How can I reverse a list in foreach?

List<T>.Reverse doesn't return anything - it reverses the list in place.

If you want to use the LINQ version of Reverse which returns a reversed sequence but without mutating the existing list, you could use:

foreach (IEnumerable<Foo> row in Items) 
{
foreach (Foo item in row.Reverse())
{
...
}
}

Or perhaps more clearly:

foreach (List<Foo> row in Items) 
{
// We want to use the LINQ to Objects non-invasive
// Reverse method, not List<T>.Reverse
foreach (Foo item in Enumerable.Reverse(row))
{
...
}
}

Python's foreach backwards

Here is a good compilation of things you could do to achieve backward iteration: http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html



Related Topics



Leave a reply



Submit