76

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. Commented 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? Commented May 7, 2012 at 15:29

2 Answers 2

184

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);
Sign up to request clarification or add additional context in comments.

7 Comments

All in one line: usort($array, function($a, $b){ return strcmp($a["name"], $b["name"]); });
@pmrotule: Only for version> PHP 5.3
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, you can also use the function strcasecmp for this. It compares strings case-insensitive. See php.net/manual/en/function.strcasecmp.php
This works perfectly until you specify the compare method inside the method scope you are using
|
19

usort is your friend:

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

usort($array, "cmp");

3 Comments

if we want age then what change will be made in function of cmp instead of strcmp?
@BhavinThummar Simply return $a["age"] - $b["age"].
Thanks @ccKep. I have solved my issue using this solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.