102

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++;
    }
?>  

9 Answers 9

212

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);
}
9
  • 2
    @Slawek If the array is already ordered, why would reversing necessarily be better than counting through it backwards?
    – Sampson
    May 27, 2012 at 22:13
  • 5
    @JonathanSampson - because if you reverse array before using it in loop, you can simply change it in future. When you bind loop logic with data, changing order will force to change also the loop.
    – Slawek
    May 27, 2012 at 22:22
  • 1
    @Slawek I'm not sure I follow. Counting backwards through an array is a common practice, and doesn't require any caution when handling the array in the future since it doesn't actually modify the array.
    – Sampson
    May 27, 2012 at 22:40
  • 1
    @Slawek I'm not in disagreement there. Thought I don't see any indication the user is following any sort of MVC pattern. Certainly, if they have a controller, or a model, it may be wiser to sort the array there in many cases.
    – Sampson
    May 28, 2012 at 0:51
  • 2
    Not very good for performance, but definitely more readable code :-)
    – eyal_katz
    Jan 9, 2020 at 4:49
35

Or you could use the array_reverse function.

0
28

array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.

<?php 
    $input = array('a', 'b', 'c');
    foreach (array_reverse($input) as $value) {
        echo $value."\n";
    }
?>

The output will be:

c
b
a

So, to address to OP, the code becomes:

<?php
    $j=1;     
    foreach ( array_reverse($skills_nav) as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
}

Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).

0
8

If you don't mind destroying the array (or a temp copy of it) you can do:

$stack = array("orange", "banana", "apple", "raspberry");

while ($fruit = array_pop($stack)){
    echo $fruit . "\n<br>"; 
}

produces:

raspberry 
apple 
banana 
orange 

I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first. Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:

$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
    echo $stack[$index] ." is in position ". $index . "\n<br>";
    $index--;
} 

But as you can see, you have to be very careful with the index...

1
  • 2
    The array_pop approach is 3 times slower than the array_reverse approach: 3v4l.org/3jaTT
    – Finesse
    Nov 11, 2018 at 10:48
5

You can use usort function to create own sorting rules

1
  • This will not be performant since the array is already in order (just reverse the order). Feb 8, 2022 at 1:55
5

Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:

$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
    echo $fruits[$i] . '<br>';
} 
2

If your array is populated through an SQL Query consider reversing the result in MySQL, ie :

SELECT * FROM model_input order by creation_date desc
0

If you do not have Boolean false values in your array, you could use next code based on internal pointer functions:

$array = ['banana', 'apple', 'pineapple', 'lemon'];

$value = end($array);
while ($value !== false) {
     // In case you need a key
    $key = key($array);

    // Do something you need to
    echo $key . ' => ' . $value . "\n";

    // Move pointer
    $value = prev($array);
}

This solution works for associative arrays with arbitrary keys and do not require altering existing or creating a new one.

-2
<?php
    $j=1; 


      array_reverse($skills_nav);   


    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?> 
1
  • 2
    array_reverse() does not alter the source array, but returns a new array. Nov 23, 2016 at 23:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.