Basel
Basel

Reputation: 369

How to sort a PHP array and using the same index for each element?

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

);

Upvotes: 2

Views: 109

Answers (1)

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
)

Upvotes: 2

Related Questions