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?

2
  • 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 7, 2012 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 7, 2012 at 15:29

2 Answers 2

180

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);
7
  • 41
    All in one line: usort($array, function($a, $b){ return strcmp($a["name"], $b["name"]); });
    – pmrotule
    Feb 26, 2014 at 15:56
  • 4
    @pmrotule: Only for version> PHP 5.3
    – Mohit
    Jul 31, 2014 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 2, 2015 at 19:27
  • 13
    @Andrew, you can also use the function strcasecmp for this. It compares strings case-insensitive. See php.net/manual/en/function.strcasecmp.php
    – Brian
    Mar 26, 2015 at 11:46
  • 2
    This works perfectly until you specify the compare method inside the method scope you are using Feb 24, 2017 at 9:08
18

usort is your friend:

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

usort($array, "cmp");
3
  • if we want age then what change will be made in function of cmp instead of strcmp? Apr 8, 2019 at 14:11
  • 1
    @BhavinThummar Simply return $a["age"] - $b["age"].
    – ccKep
    Apr 8, 2019 at 18:53
  • Thanks @ccKep. I have solved my issue using this solution. Apr 10, 2019 at 4:59

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