PHP: Sort array alphabetically using a string/value in subarray

PHP: Sort array alphabetically using a string/value in subarray

 
 

If we have an array and inside each value of this array we have another array with age and name for example, and we want to sort the first array by the name of each value in the child arrays we do is using usort  and strcmp functions from php.

Here is an example:

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

This will output:

    Array
(
    [0] => Array
        (
            [name] => Bill
            [age] => 15
        )

    [1] => Array
        (
            [name] => Nina
            [age] => 21
        )

    [2] => Array
        (
            [name] => Peter
            [age] => 17
        )

)
 
 

tags: php arrays sort


We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .