简体   繁体   中英

sort indexed array into descending order by index in php

I am trying to list the contents in the reverse order to that in which they were defined.

The language is PHP Version 5.6.3

I'm using the following code:

$cars = array("Volvo", "BMW", "Toyota", "Chevy");
$arrayCount = count($cars);

krsort($cars);

for($idx = 0; $idx < $arrayCount; $idx++) {
    echo $cars[$idx];
    echo "<br>";
}

I get:

Volvo
BMW
Toyota
Chevy

And not the expected:

Chevy
Toyota
BMW
Volvo

Any help would be greatly appreciated!

Use array_reverse

It will do your job.

Simply can use array_reverse() . Example:

$cars = array("Volvo", "BMW", "Toyota", "Chevy");
$reversed = array_reverse($cars);

array_walk($reversed, function($val, $key){ echo $val . "\n"; });

Or can use foreach() instead of array_walk()

foreach($reversed as $k=>$v){
    echo $v . "\n";
}

Output:

Chevy
Toyota
BMW
Volvo

Why not just use array_reverse() ?

$cars = array("Volvo", "BMW", "Toyota", "Chevy");
$reversed = array_reverse($cars);
var_dump($reversed);

This should work for you:

<?php

    $cars = array("Volvo", "BMW", "Toyota", "Chevy");
    $cars = array_reverse($cars);

    foreach($cars as $k => $v)
        echo $cars[$k] . "<br />";

?>

Output:

Chevy
Toyota
BMW
Volvo

you can use array_reverse()

$cars = array("Volvo", "BMW", "Toyota", "Chevy");
$reversed = array_reverse($cars, true); //reverses array and keeps keys

$arrayCount = count($reversed);    

for($idx = 0; $idx < $arrayCount; $idx++)
{
   echo $cars[$idx];
   echo "<br>";
}

This will work!

You can use array_reverse as some others already said or you can instead of ++ your for loop -- it.

$cars = array("Volvo", "BMW", "Toyota", "Chevy");
$arrayCount = count($cars);

krsort($cars);

for($idx = $arrayCount; $idx > 0; $idx--)
  {
    echo $cars[$idx];
    echo "<br>";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM