Case Insensitively Sort a Multidimensional PHP Array using array_multisort()

arrays, case-insensitive, php, sorting

Solution

I should note this only works in php 5.4+

# Example results from database
$PDOresult = array(
    array('name' => 'Alpha', 'price' => '10'),
    array('name' => 'beta', 'price' => '12'),
    array('name' => 'Gamma', 'price' => '14'),
    array('name' => 'delta', 'price' => '16'),
    array('name' => 'Epsilon', 'price' => '18'),
    array('name' => 'zeta', 'price' => '20'),
    ...
);

# Create array of field to sort by - 'name' in this example
foreach ($PDOresult as $key => $row) {
    $sort_by[$key] = $row['name'];
}

# Sort array - The flags SORT_NATURAL & SORT_FLAG_CASE are required to make the
# sorting case insensitive.
array_multisort($sort_by, SORT_ASC, SORT_NATURAL|SORT_FLAG_CASE, $PDOresult);

# Output
var_dump($PDOresult);

If using php 5.5+ you can skip the `foreach()` and use array_column() instead. Like so:

$sort_by = array_column($PDOresult, 'name');

I was tempted to edit this into the well written answer: How can I sort arrays and data in PHP? but I didn't want to screw up the formatting so if someone wants to do that and close this, that would be fine with me.

Problem

After much searching I haven't been able to find a good explanation on how to use array_multisort() to case insensitively sort a multidimensional array by one field. I find this to be a very helpful feature when dealing with information from database queries so thought I would share.

Original source