Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing PHP array ksort

Tags:

arrays

php

ksort

I have an array which is like this:

Array(
    [31] => 1
    [30] => 2
    [29] => 3
    [28] => 4
)

I then use ksort($array) which sorts it as 28, 29, 30, and 31 but the problem with this is the numbers 1-4 go with the values so get reversed. I want 28 to become 1, 29 to become 2 etc.

Is there a way without creating a foreach loop and reconstructing a new array to make this switch?

like image 800
John Avatar asked Feb 21 '26 13:02

John


1 Answers

You can flip the array, sort it, and then flip it back:

$array = array(31 =>1, 30 => 2, 29 => 3, 28 => 4);

$result = array_flip($array);
sort($result);
$result = array_flip($result);

This results in an array sorted by keys, and values integers starting from 0:

Array (
    [28] => 0
    [29] => 1
    [30] => 2
    [31] => 3
)

Maintaining existing values

If you want to maintain your existing values then use the array_combine function to merge the sorted keys with the old values:

$result = array_flip($array);
sort($result);
$result = array_combine($result, $array);

The resulting array is then:

Array
(
    [28] => 1
    [29] => 2
    [30] => 3
    [31] => 4
)
like image 181
Eborbob Avatar answered Feb 23 '26 03:02

Eborbob