Sign In

Write an Article


How To Sort An Array With A User Defined Comparison Function And Maintain Index Association In Php ?

Publish in Web Development June 21, 2025

PHP gives us lot of array functions but when we want to sort an array in easier way. Here is the simple function that is uasort(). The uasort() function sort an array with user defined comparison function and can also easily maintain index association.

Now, How to sort an array in place which its keys maintain their connection with the values they are associated. (user defined comparison function).

Parameters:- function has only two parameters which is mention below.

  • Array :- The input value is in array.
  • Callback:- Required comparison function must return an integer like (0-9) less than and equal to, or greater than 0 if the first argument is considered to be respectively less than, equal to, or greater than the second.

Syntax

uasort($array, callback);

Example:-

<?php

function comparisonFunction($b, $c) {
	if ($b == $c) {
		return 0;
	}
	return ($b < $c) ? -1 : 1;
}

// Array to be sorted

$array = array(
		'a' => 9, 
		'b' => 2, 
		'c' => -3, 
		'd' => -9, 
		'e' => 6, 
		'f' => 5, 
		'g' => 7, 
		'h' => -4
	);

// Sort and print the resulting array

uasort($array, 'comparisonFunction');

print_r($array);

?>

You can see the results:

Array ( [d] => -9 [h] => -4 [c] => -3 [b] => 2 [f] => 5 [e] => 6 [g] => 7 [a] => 9 )