Two ways to sort an array keeping its key in php

The sort function in array sorts the array very well, but it doesnt maintain the keys so that it becomes really painful sometimes. There will be several scenarios were we need to keep the keys of the associative arrays.

Luckily there are two functions in php which will help us to achieve this

1. uasort

uasort sort the array in the desired order (ascending or descending and will maintain the keys). It accepts two arguments,
1. The array to be sorted
2. The compare function

  $b) ? -1 : 1; 
        }  // Array to be sorted echo" pre="">";
        	
        $array = array('a' => 3, 'b' => 1, 'c' => -1, 'd' => -2, 'e' => 2, 'f' => -3, );
        echo "
";
        echo "Array Before Sorting 
"; print_r($array); echo "
"; // Sort and print the resulting array uasort($array, 'compare'); echo "Array After Sorting
"; print_r($array); ?>

The compare function return 1 or -1 which comes as the outcome of the bigger or smaller values(in the array) which has been compared.
Output

Array Before Sorting 
Array
(
    [a] => 3
    [b] => 1
    [c] => -1
    [d] => -2
    [e] => 2
    [f] => -3
)

Array After Sorting 
Array
(
    [a] => 3
    [e] => 2
    [b] => 1
    [c] => -1
    [d] => -2
    [f] => -3
)

2. asort

asort sorts the array and maintains its key. The sorting will only be in ascending order (from smallest to largest). We may need to reverse the array in order to sort it in the descending order. For that we can use the array_reverse function in php

About the author

Linjo Joson

Linjo is a PHP developer who loves to write about online businesses and marketing ideas

Add comment

Categories