77

Possible Duplicate:
How can I sort arrays and data in PHP?
How do I sort a multidimensional array in php
PHP Sort Array By SubArray Value
PHP sort multidimensional array by value

My array looks like:

Array(
    [0] => Array(
         [name] => Bill
         [age] => 15
    ),
    [1] => Array(
         [name] => Nina
         [age] => 21
    ),
    [2] => Array(
         [name] => Peter
         [age] => 17
    )
);

I would like to sort them in alphabetic order based on their name. I saw PHP Sort Array By SubArray Value but it didn't help much. Any ideas how to do this?

deceze
  • 510,633
  • 85
  • 743
  • 889
user6
  • 1,999
  • 2
  • 23
  • 29
  • 3
    The question you linked contains the exact answer you need.. just replace `'optionNumber'` with `'name'` in the comparison function. Voting to close as duplicate. If there's something in the other question you don't understand please ask specifically about that. – Mike B May 07 '12 at 15:21
  • I've never seen an array that has the same key for two values. Probably that's why the sort does not work? – hakre May 07 '12 at 15:29

2 Answers2

179

Here is your answer and it works 100%, I've tested it.

<?php
$a = Array(
    1 => Array(
         'name' => 'Peter',
         'age' => 17
    ),
    0 => Array(
         'name' => 'Nina',
         'age' => 21
    ),
    2 => Array(
         'name' => 'Bill',
         'age' => 15
    ),
);
function compareByName($a, $b) {
  return strcmp($a["name"], $b["name"]);
}
usort($a, 'compareByName');
/* The next line is used for debugging, comment or delete it after testing */
print_r($a);
DrCord
  • 3,917
  • 3
  • 34
  • 47
Marian Zburlea
  • 9,177
  • 4
  • 31
  • 37
  • 40
    All in one line: usort($array, function($a, $b){ return strcmp($a["name"], $b["name"]); }); – pmrotule Feb 26 '14 at 15:56
  • 4
    @pmrotule: Only for version> PHP 5.3 – Mohit Jul 31 '14 at 18:53
  • 17
    Worth noting that strcmp is case-sensitve. Took me a while to figure out why sorting alphabetically wasn't giving the expected results. I changed the above code to return the following: return strcmp(strtolower($a["name"]), strtolower($b["name"])); – Andrew Mar 02 '15 at 19:27
  • 13
    @Andrew, you can also use the function **strcasecmp** for this. It compares strings case-insensitive. See http://php.net/manual/en/function.strcasecmp.php – Brian Mar 26 '15 at 11:46
  • 2
    This works perfectly until you specify the compare method inside the method scope you are using – Juliyanage Silva Feb 24 '17 at 09:08
  • $a is ambiguous ...is i s the same array? – Francesco Oct 22 '17 at 18:51
  • 1
    Use 'uasort' if you want preserve index values – Channel May 28 '18 at 14:37
18

usort is your friend:

function cmp($a, $b)
{
        return strcmp($a["name"], $b["name"]);
}

usort($array, "cmp");
ccKep
  • 5,786
  • 19
  • 31