PHP sort associative array using custom compare function

PHP associative array can be sorted using custom user compare function while maintaining index association using uasort. The function is passed two values and it should return these return values.

  • -1 if value1 should appear before value2
  • 0 if value1 = value2
  • 1 if value1 should appear after value2

Here is example code where associative array contains employee id as key and age and city in value. This example will sort array by employee age.

<?php
// employee id, age, city data
$arr = array(
  '101' => array(39, "Bangalore"),
  '105' => array(29, "Delhi"),
  '109' => array(35, "Delhi"),
);
uasort($arr, function($a, $b) {
  if ($a[0] < $b[0]) {
    return -1;
  } else if ($a[0] == $b[0]) {
    return 0;
  } else {
    return 1;
  }
});
print_r($arr);
?>
Array
(
    [105] => Array
        (
            [0] => 29
            [1] => Delhi
        )

    [109] => Array
        (
            [0] => 35
            [1] => Delhi
        )

    [101] => Array
        (
            [0] => 39
            [1] => Bangalore
        )

)
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments