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.

// 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;
Env: PHP 5.5.9 (Linux)

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


Click here to write/view comments