Shuttleu
Shuttleu

Reputation: 123

Retun order of keys from sorted array PHP

I have a array in PHP like so

$somevar = array(1, 5, 2, 7, 17, 2, 13);

I want to sort the array, but not move the values around, so I get another array with the order of the index/keys.

So my new array would be something like

{0, 2, 5, 1, 3, 6, 4}

Which is the order of the keys

Upvotes: 3

Views: 51

Answers (2)

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this..

$somevar = array(1, 5, 2, 7, 17, 2, 13);
print_r($somevar);
//your array
Array ( [0] => 1 [1] => 5 [2] => 2 [3] => 7 [4] => 17 [5] => 2 [6] => 13 )
asort($somevar);
print_r($somevar);
//After sort
Array ( [0] => 1 [2] => 2 [5] => 2 [1] => 5 [3] => 7 [6] => 13 [4] => 17 ) 
print_r(array_keys($somevar));
//array key sorted array
Array ( [0] => 0 [1] => 2 [2] => 5 [3] => 1 [4] => 3 [5] => 6 [6] => 4 )

Upvotes: 2

Rizier123
Rizier123

Reputation: 59681

This should work for you:

<?php

    $somevar = array(1, 5, 2, 7, 17, 2, 13);
    $newArray = array_values($somevar);
    asort($newArray);
    $newArray = array_keys($newArray);
    print_r($newArray);

?>

Output:

Array ( [0] => 0 [1] => 2 [2] => 5 [3] => 1 [4] => 3 [5] => 6 [6] => 4 )

Upvotes: 3

Related Questions