How can I sort this array by the value of the "order" key? Even though the values are currently sequential, they will not always be.

Array([0]=> Array([hashtag]=> a7e87329b5eab8578f4f1098a152d6f4[title]=> Flower[order]=> 3)[1]=> Array([hashtag]=> b24ce0cd392a5b0b8dedc66c25213594[title]=> Free[order]=> 2)[2]=> Array([hashtag]=> e7d31fc0602fb2ede144d18cdffd816b[title]=> Ready[order]=> 1))
up vote1444down voteaccepted

Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

function sortByOrder($a, $b) {return $a['order'] - $b['order'];}usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {return $a['order'] - $b['order'];});

And finally with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {return $a['order'] <=> $b['order'];});

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) {$retval=$a['order'] <=> $b['order'];if ($retval==0) {$retval=$a['suborder'] <=> $b['suborder'];if ($retval==0) {$retval=$a['details']['subsuborder'] <=> $b['details']['subsuborder'];}}return $retval;});

If you need to retain key associations, use uasort() - see comparison of array sorting functions in the manual

  • 2
    My phrasing is a little bit off, I'll edit it. What I meant is that if you're not on PHP 5.3, you need to create a special function just for this particular sorting (Which is somehow not very elegant). Otherwise you could use an anonymous function right there.– Christian StuderApr 24 '10 at 4:40
  • 22
    @Jonathan: You can't really see most of the work PHP does. It takes the array and starts with two elements, which it passed to this user defined function. Your function is then responsible to compare them: If the first element is bigger than the second, return a positive integer, if it is smaller, return a negative one. If they are equel, return 0. PHP then sends two other elements to your function and continues to do so, until the array has been sorted. The function here is very short, it might be much more complicated if you wouldn't be comparing integers.– Christian StuderFeb 13 '12 at 10:40
  • 46
    Protip: use uasort() if you want to preserve the array keys.– thaddeusmtApr 30 '13 at 23:54
  • 15
    Be careful if the sortable values are decimal numbers. If the sorting function get's $a=1 and $b=0.1, the difference is 0.9, but the function returns an int, in this case 0, so $a and $b are considered equal and sorted incorrectly. It's more reliable to compare if $a is bigger than $b or equal, and return -1, 1 or 0 accordingly.– GreenlandiJul 12 '13 at 6:45
  • 27
    It took me a while to find out. To sort the reverse order (DESC) you can switch $a and $b. So $b['order'] - $a['order']– JanWillemFeb 2 '14 at 17:54
function aasort (&$array, $key) {$sorter=array();$ret=array();reset($array);foreach ($array as $ii=> $va) {$sorter[$ii]=$va[$key];}asort($sorter);foreach ($sorter as $ii=> $va) {$ret[$ii]=$array[$ii];}$array=$ret;}aasort($your_array,"order");
  • 6
    @noc2spam I'm glad to help, but consider following studer's suggestion which is likely more efficient and surely more tidy!– o0'.Jul 15 '13 at 14:14
  • 1
    @Lohoris sure dude I am checking that out too. Yesterday would have been a tougher day in the office if I didn't find this question :-)– SugatoJul 16 '13 at 10:21
  • hmm cant add an answer.. well I put it here coz I dont need those stupid points: so for a multidimensional sort its (almost) the same thing (srry you have to copy paste and reformat it): function aasort (&$array, $key1, $key2, $key3) { $sorter=array(); $ret=array(); reset($array); foreach ($array as $ii=> $va) { $sorter[$ii]=getPrice($va[$key1][$key2][$key3]); } arsort($sorter); foreach ($sorter as $ii=> $va) { $ret[$ii]=$array[$ii]; } $array=$ret; }– Rudolf ReinMay 21 '14 at 16:43
  • 3
    Much easier to apply than above answer– MarcelFeb 9 '16 at 16:51
  • Works great for PHP 5.9– Daniyal NasirJul 4 at 12:13

I use this function :

function array_sort_by_column(&$arr, $col, $dir=SORT_ASC) {$sort_col=array();foreach ($arr as $key=> $row) {$sort_col[$key]=$row[$col];}array_multisort($sort_col, $dir, $arr);}array_sort_by_column($array, 'order');
  • 2
    Works very well. The unique solution being able to add a sort direction. Thanks!– Ivo PereiraMay 8 '13 at 10:43
  • 2
    For an alternative that supports sort directions and a lot of additional features, you might want to take a look at my answer here -- it also has the advantage that it does not use array_multisort and thus does not need to preallocate $sort_col, saving on time and memory.– JonMay 28 '13 at 9:59
  • 2
    @RaduMurzea so the array is passed by reference and can be modified by the function, rather than the function receiving a copy– Tom HaighAug 10 '13 at 10:58
  • 1
    this works for float column, too– 6opkoMar 4 '15 at 11:05
  • 1
    @AdrianP. : the array is passed by reference so it will modify the passed array rather than returning a sorted copy– Tom HaighMay 16 '16 at 15:35

I usually use usort, and pass my own comparison function. In this case, it is very simple:

function compareOrder($a, $b){return $a['order'] - $b['order'];}usort($array, 'compareOrder');
  • 4
    Dammit, I was 30 seconds slower. Isn't it $a - $b though?– Christian StuderApr 23 '10 at 14:06
  • 3
    I always get this wrong. Let me think from the manual: the return value must be less than zero if the first argument is considered less than the second. So if $a['order'] is 3, and $b['order'] is 6, I will return -3. Correct?– Jan FabryApr 23 '10 at 14:22
  • 3
    Well, you return b - a, so it will be 3. And thus sorted incorrectly.– Christian StuderApr 23 '10 at 15:10
  • 25
    Ah. OK. I was using non-logical arithmetic, where the idea in your head does not match the words you produce. This is studied most frequently on Friday afternoons.– Jan FabryApr 23 '10 at 21:02
  • in some case above answer is return wrong result.. reference…– Bilal AhmedJun 1 at 6:32
$sort=array();$array_lowercase=array_map('strtolower', $array_to_be_sorted);array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);

This takes care of both upper and lower case alphabets.

  • 4
    How does this answer the question of sorting by a particular array key?– SeanoAug 16 '16 at 8:41

To sort the array by the value of the "title" key use:

uasort($myArray, function($a, $b) {return strcmp($a['title'], $b['title']);});

strcmp compare the strings.

uasort() maintains the array keys as they were defined.

    One approach to achieve this would be like this

     $new=[['hashtag'=> 'a7e87329b5eab8578f4f1098a152d6f4','title'=> 'Flower','order'=> 3,],['hashtag'=> 'b24ce0cd392a5b0b8dedc66c25213594','title'=> 'Free','order'=> 2,],['hashtag'=> 'e7d31fc0602fb2ede144d18cdffd816b','title'=> 'Ready','order'=> 1,],];$keys=array_column($new, 'order');$result=array_multisort($keys, SORT_ASC, $new);


     Array([0]=> Array([hashtag]=> e7d31fc0602fb2ede144d18cdffd816b[title]=> Ready[order]=> 1)[1]=> Array([hashtag]=> b24ce0cd392a5b0b8dedc66c25213594[title]=> Free[order]=> 2)[2]=> Array([hashtag]=> a7e87329b5eab8578f4f1098a152d6f4[title]=> Flower[order]=> 3))

      The most flexible approach would be using this method

      Arr::sortByKeys(array $array, $keys, bool $assoc=true): array

      here's why:

      • You can sort by any key (also nested like 'key1.key2.key3' or ['k1', 'k2', 'k3'])

      • Works both on associative and not associative arrays ($assoc flag)

      • It doesn't use reference - return new sorted array

      In your case it would be as simple as:

      $sortedArray=Arr::sortByKeys($array, 'order');

      This method is a part of this library.

        Let's face it: php does NOT have a simple out of the box function to properly handle every array sort scenario.

        This routine is intuitive, which means faster debugging and maintenance:

        // automatic population of array$tempArray=array();$annotations=array();// ... some code// SQL $sql retrieves result array $result // $row[0] is the ID, but is populated out of order (comes from // multiple selects populating various dimensions for the same DATE // for examplewhile($row=mysql_fetch_array($result)) {$needle=$row[0];arrayIndexes($needle); // create a parallel array with IDs only$annotations[$needle]['someDimension']=$row[1]; // whatever}asort($tempArray);foreach ($tempArray as $arrayKey) {$dataInOrder=$annotations[$arrayKey]['someDimension']; // .... more code}function arrayIndexes ($needle) {global $tempArray;if (!in_array($needle,$tempArray)) {array_push($tempArray,$needle);}}
        • 2
          "Let's face it: php does NOT have a simple out of the box function to properly handle every array sort scenario." That's exactly what usort/ksort/asort are designed for ^^'– Ben CassinatApr 23 at 13:19
        • QED. thanks for the support. ;)– tony gilApr 23 at 19:46
        • 2
          Actually PHP has a lot of sorting functions that can be used to handle every array sort scenario.– axiacMay 29 at 16:31
        • PLEASE ENLIGHTEN WITH EXAMPLES!!! tks– tony gilMay 29 at 21:25

        protected by Abdulla Nilam Mar 13 at 9:29

        Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

        Would you like to answer one of these unanswered questions instead?

        Not the answer you're looking for? Browse other questions tagged or ask your own question.