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))
{
...
}
}
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.
Traverse a list in reverse order in Python
Use the built-in reversed()
function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
To also access the original index, use enumerate()
on your list before passing it to reversed()
:
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
Since enumerate()
returns a generator and generators can't be reversed, you need to convert it to a list
first.
How to reverse foreach $key value PHP?
$layercount = count($array);
foreach ($array as $key => $layer){
// css z-index: $key reversed
$zIndex = $layercount - 1 - $key;
}
making a list that maintains a reverse order by its own
Your ReverseIterator
is a subclass of ReverseList
. This means, it is a list on its own. Then, you are mixing up the state of these two lists. In the ReverseIterator(ReverseList<E> r)
, you use r
’s size to initialize pos
, in next()
you use super.get(pos--)
, accessing the other list’s content. This other list is always empty.
An iterator should never be a collection. When you implement an iterator as an inner class, you can access the outer collection’s state implicitly.
Besides that, your list clearly violates the contract of the List
interface and will cause a lot of other problems in the future, as its iterator()
is inconsistent with other List
features, like all index based operations or listIterator()
.
You should not change the fundamentals of a class, just for the sake of a single operation (i.e. iterate backwards). Rather, implement this single operation as a distinct operation.
For example:
public class ReversibleList<T> extends ArrayList<T> {
private class ReverseIterator implements Iterator<T> {
private int pos = size() - 1;
@Override
public boolean hasNext() {
return pos >= 0;
}
@Override
public T next() {
return get(pos--);
}
}
public Iterable<T> reverse() {
return () -> new ReverseIterator();
}
public static void main(String[] args) {
ReversibleList<Integer> r = new ReversibleList<>();
r.add(1);
r.add(2);
r.add(3);
r.add(4);
for(Integer i: r.reverse()) {
System.out.println(i);
}
}
}
The reverse()
view has no storage of its own but always reflects the current contents of the list, in reverse order. The original List
keeps fulfilling its contract.
Note that it is possible to create reversed view to a list supporting other operations of the List
interface beyond iterator()
:
public class ReversibleList<T> extends ArrayList<T> {
private class ReversedList extends AbstractList<T> implements RandomAccess {
@Override
public T get(int index) {
return ReversibleList.this.get(size() - index - 1);
}
@Override
public int size() {
return ReversibleList.this.size();
}
}
public List<T> reverse() {
return new ReversedList();
}
public static void main(String[] args) {
ReversibleList<Integer> r = new ReversibleList<>();
r.add(1);
r.add(2);
r.add(3);
r.add(4);
r.reverse().subList(1, 4).stream().forEach(System.out::println);
}
}
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);
}
Related Topics
How to Bind Decimal/Double/Float Values with Pdo in PHP
How to Convert PHP Regex to JavaScript Regex
Change Innerhtml of a PHP Domelement
Get Number of Rows Matched by Update Query with PHP MySQLi
Explode a Paragraph into Sentences in PHP
Laravel 4.1: How to Paginate Eloquent Eager Relationship
PHP File_Get_Contents Does Not Work on Localhost
PHP Array_Intersect() Efficiency
How to Download a File Using Curl in PHP
How to Login Using Github, Facebook, Gmail and Twitter in Laravel 5.1
How to Check If an Integer Is Within a Range of Numbers in PHP
How to Make Form_Rest() Not Display a Field with Symfony2
PHP Not Loading PHP_Pgsql.Dll on Windows
What's the Best Way to Create a Single-File Upload Form Using PHP