By stef

2010-04-23 13:54:26 8 Comments

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.

    [0] => Array
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [order] => 3

    [1] => Array
            [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
            [title] => Free
            [order] => 2

    [2] => Array
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1


@Jan Fabry 2010-04-23 14:04:17

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');

In PHP 7 using spaceship operator:

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

@Christian Studer 2010-04-23 14:06:50

Dammit, I was 30 seconds slower. Isn't it $a - $b though?

@Jan Fabry 2010-04-23 14:22:21

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?

@Christian Studer 2010-04-23 15:10:59

Well, you return b - a, so it will be 3. And thus sorted incorrectly.

@Jan Fabry 2010-04-23 21:02:47

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.

@Bilal Ahmed 2018-06-01 06:32:00

in some case above answer is return wrong result.. reference…

@Ghanshyam Nakiya 2019-06-13 10:01:10

Use array_multisort(), array_map()

array_multisort(array_map(function($element) {
      return $element['order'];
  }, $array), SORT_ASC, $array);



@Kami Yang 2020-04-22 11:42:25

Note that this approach will emit a notice. array_multisort references it’s first parameter.

@ajuchacko91 2018-07-04 13:30:26

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');

    array_multisort($keys, SORT_ASC, $new);



        [0] => Array
                [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
                [title] => Ready
                [order] => 1

        [1] => Array
                [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
                [title] => Free
                [order] => 2

        [2] => Array
                [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
                [title] => Flower
                [order] => 3


@Brian Cugelman 2020-07-19 23:22:42

Sweet. What I like about this solution is the extra array is built by PHP's native function making it much faster, and you have the full set of options from multisort. Great basis for a custom sorting function. Thanks.

@ahmednawazbutt 2020-07-28 13:52:39

simple yet brilliant. Hats off

@Christian Studer 2010-04-23 14:04:55

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

@Christian Studer 2010-04-24 04:40:54

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 Studer 2012-02-13 10:40:14

@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.

@Karl Adler 2012-10-17 17:16:40

in my case your solution is buggy. The first column is excluded of sorting. Could you check it?

@thaddeusmt 2013-04-30 23:54:44

Protip: use uasort() if you want to preserve the array keys.

@Greenlandi 2013-07-12 06:45:28

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.

@Llewellyn 2013-10-19 14:58:21

This works great, I had a multi multidimensional array to sort. And this worked excellent! This is how I used it usort($subArray, function($b, $a) { return $a['c'][5]['v'] - $b['c'][5]['v']; });

@Joeri 2013-11-04 10:41:33

Nice if you include the key as a constant. The solution of Lohoris has the key as a variable, making the function more abstract and reusable.

@JanWillem 2014-02-02 17:54:35

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']

@craphunter 2014-04-12 11:02:19

Why do you need a version for PHP 5.3 or higher?

@Christian Studer 2014-04-22 08:01:56

@craphunter: The PHP 5.2 version also works on PHP 5.3, it's just less elegant.

@Ajit Kumar 2014-12-11 19:13:20

for any element of the array you want to sort : $name = 'order';//defined the name which use for sort usort($myArray, function ($a, $b) use(&$name){ return $a[$name] - $b[$name];});

@user3567805 2015-05-12 09:26:55

i have confuse about $a and $b array. From where $a and $b will received in sortByOrder($a, $b) function.

@user956584 2015-07-15 11:28:40

Most funny think this not working usort(@$myArray, function($a, $b) ,,, WHY usort don't like (AT)

@Vinoth Kumar 2015-10-16 02:59:10

Hi guys, Am new to PHP, can any one please explain me, this line => return $a['order'] - $b['order']; will it subtract or compare ?

@Christian Studer 2015-10-16 06:20:04

@VinothKumar Please read the fourth comment for an explanation of what exactly happens here.

@Vinoth Kumar 2015-10-16 09:44:34

@ChristianStuder: thank you.. I really break my head for a while.. Now I got. Positive, Negative and Zero. Awesome...

@Nishad Up 2015-11-16 08:05:33

In CodeIgniter I am getting warning > usort() expects parameter 2 to be a valid callback, function 'sortByOrder' not found or invalid function name

@Gideon Sassoon 2016-03-23 18:01:54

Worked like a fantastic charm. Note if you want to sort items further down your array you can it and it will shift everything correctly :D usort($mile2['milestones'], function($a, $b) { return $a['start_time']['date'] - $b['start_time']['date']; });

@Anthony Rutledge 2016-04-03 13:35:56

Ha! I love the spaceship operator finale. Great job.

@jeepwran 2016-08-01 20:54:18

@thaddeusmt- thanks! was wondering what was happening to my keyed array after just usort(). uasort() works like a charm.

@zzapper 2016-08-22 16:54:29

I had been using plain vanilla "sort" on my structure without any "apparent" problems. I think that was maybe "luck" because as soon as my array got bigger the ordering went crazy. The above solution worked beautifully @[email protected]

@bbe 2016-11-11 17:37:47

for ordering string values, use: {return strcmp(strtolower($a['order_string']), strtolower($b['order_string']));} (It's somebody's answer at stackoverflow, but its right place is here).

@John Hunt 2016-11-28 11:54:19

Spaceship operator +1

@matasoy 2017-11-26 20:33:32

My mouth is still open, thanks for this simple magic answer. I use this to order function sortByOrder($a, $b) { return $b[1] - $a[1]; } usort($anahtarlar, 'sortByOrder');

@Er.KT 2018-01-15 18:37:15

what else you needed, just an awesome.

@Marco 2018-01-15 18:38:47

Take care using return $a['dummy'] - $b['dummy']: Try it with these array: $array = []; $array[] = array("dummy" => -10.19); $array[] = array("dummy" => -10.05); $array[] = array("dummy" => -10.21); Use when possible the spaceship operator or return (floatval($a['dummy']) < floatval($b['dummy'])) ? -1 : 1;

@kry 2018-02-26 13:41:40

Thank you for your patronage.

@Avi Kehat 2018-05-28 14:02:57

I have PHP 7 on my server, yet I'm still getting: Parse error: syntax error, unexpected '>' in ... Changing the spaceship to "minus" - does not result in a correct sort.

@Avi Kehat 2018-05-28 15:18:11

Thanks @Marco - your solution was a lifesaver!

@Bilal Ahmed 2018-06-01 06:30:44

don't use second script (usort($myArray, function($a, $b) { return $a['order'] - $b['order']; });) .. because read this question…

@Kamlesh 2019-11-21 10:33:45

Not working in case sort by String value of inner array, kindly share any solution. Thanks.

@Naveenbos 2020-03-25 12:10:34… can you please check this question? I want to sort by distance without changing the sort order value

@Minwork 2018-09-06 18:10:57

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.

@tony gil 2018-04-03 11:36:28

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 example
while($row = mysql_fetch_array($result)) {
    $needle = $row[0];
    arrayIndexes($needle);  // create a parallel array with IDs only
    $annotations[$needle]['someDimension'] = $row[1]; // whatever
foreach ($tempArray as $arrayKey) {
    $dataInOrder = $annotations[$arrayKey]['someDimension']; 
    // .... more code

function arrayIndexes ($needle) {
    global $tempArray;
    if (!in_array($needle,$tempArray)) {

@benftwc 2018-04-23 13:19:24

"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 ^^'

@axiac 2018-05-29 16:31:40

Actually PHP has a lot of sorting functions that can be used to handle every array sort scenario.

@fyrye 2019-05-01 15:50:27

With regard to debugging and maintenance, the use of global is a huge red flag and is generally discouraged. Why is mysql_fetch_array being demonstrated for this question instead of the OP's source array, and that there is no explanation of what your code is doing and what one can expect the outcome to be? Overall this is a very complex approach at achieving the desired end result.

@fyrye 2019-05-02 21:07:33

@tonygil I am not able to determine what your expected results are from your answer and the the OP's dataset. It may be obvious to you, but I do not know how your answer answers the OP's question. However, you can pass by-reference instead of using global see: This produces an explicitly defined variable, rather than one that can be changed and accessed globally.

@B.K 2018-03-13 10:35:21

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.

@StudioX 2020-03-27 04:01:21

strcmp is a notable help for varchar types, i liked this answer for short and fast

@Nitrodbz 2012-02-22 20:59:05

$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.

@Seano 2016-08-16 08:41:03

How does this answer the question of sorting by a particular array key?

@Tom Haigh 2010-04-23 14:03:47

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');

@Ivo Pereira 2013-05-08 10:43:08

Works very well. The unique solution being able to add a sort direction. Thanks!

@Jon 2013-05-28 09:59:32

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.

@Radu Murzea 2013-08-10 09:00:08

Works great for me, but... why is it necessary to specify &$arr instead of just $arr ?

@Tom Haigh 2013-08-10 10:58:49

@RaduMurzea so the array is passed by reference and can be modified by the function, rather than the function receiving a copy

@HelpNeeder 2015-07-28 00:33:13

This is case sensitive, and will leave some entries unsorted.

@Norkos 2015-10-23 06:58:39

This is a better solution, because usort is really slow!

@Fakhruddin Ujjainwala 2016-03-02 13:28:46

@TomHaigh worked well for me too. Just wanted to know if it will work well in case of neg nos as well.

@Adrian P. 2016-05-16 14:43:39

Missing return $arr; to your function? Thanks.

@Tom Haigh 2016-05-16 15:35:00

@AdrianP. : the array is passed by reference so it will modify the passed array rather than returning a sorted copy

@Diego Somar 2016-12-09 01:33:08

Absolutely, the best alternative. It is very flexible. We can sort by specific key EASILY and define the order ASC or DESC. Amazing solution, tks!

@Clinton 2018-10-23 10:48:02

Nice function, it also preserves keys in the base array which is a big plus.

@fyrye 2019-05-01 16:05:34

One suggestion would be to add in the sort flags option, so that you can specify SORT_NATURAL or SORT_NUMERIC, and retain the array_multisort functionality. Like array_sort_by_column(&$arr, $col, $dir = SORT_ASC, $flags = SORT_REGULAR) { /*...*/ array_multisort($sort_col, $dir, $flags, $arr); }

@o0'. 2010-04-23 13:57:03

function aasort (&$array, $key) {
    foreach ($array as $ii => $va) {
    foreach ($sorter as $ii => $va) {


@o0'. 2013-07-15 14:14:29

@noc2spam I'm glad to help, but consider following studer's suggestion which is likely more efficient and surely more tidy!

@Gogol 2013-07-16 10:21:53

@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 :-)

@Jaxx0rr 2014-05-21 16:43:52

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; }

@Marcel 2016-02-09 16:51:06

Much easier to apply than above answer

@Daniyal Nasir 2018-07-04 12:13:37

Works great for PHP 5.9

@Kamlesh 2019-11-21 10:36:47


Related Questions

Sponsored Content

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6974005 View
  • 8528 Score
  • 97 Answer
  • Tags:   javascript arrays

49 Answered Questions

[SOLVED] How to check if an object is an array?

37 Answered Questions

[SOLVED] Create ArrayList from array

30 Answered Questions

[SOLVED] How to append something to an array?

41 Answered Questions

[SOLVED] For-each over an array in JavaScript

47 Answered Questions

[SOLVED] Sort array of objects by string property value

53 Answered Questions

30 Answered Questions

[SOLVED] Sorting an array of objects by property values

36 Answered Questions

[SOLVED] How can I pair socks from a pile efficiently?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

Sponsored Content