Alex Rivera | Logout

Alphabetically sort a flat associative array by values and preserve the original keys

Asked 2009-11-04T11:37:52.257
50

I want to sort a flat, associative array by its values alphabetically and preserve the original keys.

$arr = [
    0 => 'Newtown',
    1 => 'Montgomery',
    2 => 'Welshpool',
    6 => 'Llanfyllin',
    7 => 'Llansanffraid',
    8 => 'Llanymynech',
    9 => 'Oswestry',
    14 => 'Oswestry Town Service',
];

would become

[
    6 => 'Llanfyllin',
    7 => 'Llansanffraid',
    8 => 'Llanymynech',
    1 => 'Montgomery',
    0 => 'Newtown',
    9 => 'Oswestry',
    14 => 'Oswestry Town Service',
    2 => 'Welshpool',
]

Any ideas?

Here's my full, actual array to sort:

$arr = [
    0 => 'Newtown',
    1 => 'Montgomery',
    2 => 'Welshpool',
    6 => 'Llanfyllin',
    7 => 'Llansanffraid',
    8 => 'Llanymynech',
    9 => 'Oswestry',
    14 => 'Oswestry Town Service',
    15 => 'Aston Way',
    16 => 'College Road',
    17 => 'Shrewsbury',
    18 => 'Royal Shrewsbury Hospital',
    19 => 'Worthen',
    20 => 'Brockton',
    22 => 'Cefn Blodwell',
    23 => 'Treflach',
    24 => 'Trefonen',
    25 => 'Morda',
    26 => 'Marches School',
    28 => 'North Shropshire College',
    37 => 'Park Hall',
    38 => 'Gobowen',
    39 => 'St Martins',
    40 => 'Ifton Heath',
    42 => 'Guilsfield',
    43 => 'Four Crosses',
    45 => 'Pant',
    46 => 'Llynclys',
    49 => 'Oswestry Town Service Schools',
    51 => 'Woodside School',
    56 => 'Whittington',
    57 => 'Babbinswood',
    58 => 'Hindford',
    59 => 'Ellesmere',
    62 => 'Forden',
    63 => 'Kingswood Cock Hotel',
    65 => 'Coleg Powys',
    85 => 'Borfa Green',
    86 => 'Bryn Siriol',
    87 => 'Maesydre School',
    92 => 'Crew Green',
    93 => 'Ford',
    104 => 'Llanrhaeadr',
    106 => 'Meifod',
    114 => 'Llangynog',
    116 => 'Llangedwyn
Edit
Report

1 Answer

10
  • If you just want to sort the array values and don't care for the keys, use sort(). This will give a new array with numeric keys starting from 0.
  • If you want to keep the key-value associations, use asort().

See also the comparison table of sorting functions in PHP.

answered 2009-11-04T11:40:30.800

Your Answer