2

I have this array:

numbers = array(
                 "1"=>2
                 "2"=>5
                 "3"=>1
                 "4"=>12

);

if I used sort(numbers) the array will become

numbers = array(
                 "1"=>1
                 "2"=>2
                 "3"=>5
                 "4"=>12

);

the indexes still in same places just sort the numbers I want to move the indexes also like the following:

numbers = array(
                 "3"=>1
                 "1"=>2
                 "2"=>5
                 "4"=>12

);
0

1 Answer 1

2

You should make use of the asort in this context.

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

<?php
$numbers = array(1=>2,2=>5,3=>1,4=>12);
asort($numbers);
print_r($numbers);

OUTPUT :

Array
(
    [3] => 1
    [1] => 2
    [2] => 5
    [4] => 12
)
Sign up to request clarification or add additional context in comments.

Comments

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.