13

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

1
  • 1
    Its pretty cool that this is possible, and down below seeing it as a one liner is also cool. What would be a use case where you want to keep the keys the same but reverse the data? Commented Aug 4, 2017 at 6:29

5 Answers 5

27

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

array_reverse actually has a second argument preserve keys which do exactly the same in one call. $rv = array_reverse($v, true);
@lifecoder You are missing the central point of the question: The keys should NOT be reversed, only the values.
12

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 ) ) );

1 Comment

Your one liner is really neat, thanks for teaching that to me!
1

Here another way;

$keys = array_keys($a);
$vals = array_reverse(array_values($a));
foreach ($vals as $k => $v) $a[$keys[$k]] = $v;

Comments

0

I think this should work..

<?php
$old = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$rev = array_reverse($old);

foreach ($old as $key => $value) {
    $new[$key] = current($rev);
    next($rev);
}

print_r($new);
?>

Comments

0

This'll do it (just wrote it, demo here):

<?php
function value_reverse($array)
{
    $keys = array_keys($array);
    $reversed_values = array_reverse(array_values($array), true);
    return array_combine($keys, $reversed_values);
}

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

print_r( value_reverse($a) );

2 Comments

The function had typos, fixed it
@guidod your edit was correct, but usually suggested edits are rejected. For more discussion on the matter please refer to this question on meta

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.