NaN
NaN

Reputation: 1306

How do I flip the values of my array?

I have this array:

Array
(
    [501] => 115
    [500] => 294
    [499] => 155

The last value, 155 should match with key 501. Essentially, I need to flip the values while preserving the key order. I've already looked and the only thing I can find is array_reverse which won't help. Do I need to break this array apart and do it myself or is there a native PHP function that will do it?


Here is what I get with I use array_reverse($myOldArray)

Array
(
    [0] => 115
    [1] => 294
    [2] => 155

I need array key 501 to match 155.

Upvotes: 1

Views: 99

Answers (2)

Xpleria
Xpleria

Reputation: 5873

Try this

$l = sizeof($arr);
for($i = 0; $i < (int) ($l/2); $i++) {
    $temp = $arr[i];
    $arr[$i] = $arr[$l-$i];
    $arr[$l-$i] = $arr[$i];
}

Upvotes: 0

John Conde
John Conde

Reputation: 219894

Use array_reverse() twice:

Takes an input array and returns a new array with the order of the elements reversed.

$new_array = array_reverse(array_reverse($array), true);

The first call reverses your values. The second one changes the keys and values so they are in the order you want.

Upvotes: 4

Related Questions