1

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

3
  • How exactly did u try the array_reverse function? Commented Dec 21, 2013 at 12:31
  • 1
    read about preserve_keys in array_reverse Commented Dec 21, 2013 at 12:31
  • I hope you didn't try to create an array with that code. Commented Dec 21, 2013 at 12:33

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

You need the ksort() or krsort() functions

1 Comment

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

Try

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.