Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse array values while keeping keys

Here is an array I have:

$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');

What I would like to do is reverse the values of the array while keeping the keys intact, in other words it should look like this:

$a = array('a' => 'a5', 'b' => 'a4', 'c' => 'a3', 'd' => 'a2', 'e' => 'a1');

How should I go about it?

P.S. I tried using array_reverse() but it didn't seem to work

like image 894
pzirkind Avatar asked Jan 17 '13 00:01

pzirkind


2 Answers

It is possible by using array_combine, array_values, array_keys and array_values. May seem like an awful lot of functions for a simple task, and there may be easier ways though.

array_combine( array_keys( $a ), array_reverse( array_values( $a ) ) );
like image 73
C. E. Avatar answered Sep 28 '22 07:09

C. E.


Some step-by-step processing using native PHP functions (this can be compressed with less variables):

$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');

$k = array_keys($a);
$v = array_values($a);

$rv = array_reverse($v);

$b = array_combine($k, $rv);

var_dump($b);

Result:

array(5) {
  'a' =>
  string(2) "a5"
  'b' =>
  string(2) "a4"
  'c' =>
  string(2) "a3"
  'd' =>
  string(2) "a2"
  'e' =>
  string(2) "a1"
}
like image 44
Sven Avatar answered Sep 28 '22 07:09

Sven