3

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

1
  • Yes I have, I've also been looking through PHP sort functions, but couldnt find anything Commented Jan 20, 2015 at 11:45

2 Answers 2

3

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

Comments

2

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 )

2 Comments

but not move the values around OP don't want to change the original array!
@Rizier123 I just gave some explanation

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.