user2780294
user2780294

Reputation: 59

How to reverse array in PHP?

I have the following array:

Array ( [2294] => 1 [2292] => 1 [2296] => 1 ) 

How can I reverse it to

Array ( [2296] => 1 [2292] => 1 [2294] => 1 ) 

TRIED array_reverse() but didn't work. What I am missing?

$array = array_reverse($array); // did not work

EDIT: I do not want numeric (order sort) I just need to reverse bottom keys to top, and vice versa

Upvotes: 1

Views: 1253

Answers (4)

Roopendra
Roopendra

Reputation: 7762

Yes You can do it by krsort in php. As you need to sort based on key

    $array = array( 2294 => 1, 2292 => 1, 2296 => 1 );
    krsort($array);

    print_r($array)

Output:-

Array
(
    [2296] => 1
    [2294] => 1
    [2292] => 1
)

Edit:- You can also achieve by set the preserve_keys parameter to TRUE in array_reverse()

   $array = array_reverse($array, TRUE);
   print_r($array);

Working Demo

Upvotes: 2

Nathan Dawson
Nathan Dawson

Reputation: 19308

Try

$array = array( 2294 => 1, 2292 => 1, 2296 => 1 );
$reversed = array_reverse( $array, true );

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76646

You need to set the preserve_keys parameter to TRUE:

$result = array_reverse($array, TRUE);
print_r($result);

Output:

Array
(
    [2296] => 1
    [2292] => 1
    [2294] => 1
)

Demo.

Upvotes: 4

stUrb
stUrb

Reputation: 6822

You have to sort on the key: look at this table

You need the ksort() or krsort() functions

Upvotes: 0

Related Questions