Sorting an array by element

Sorting an array by a particular element can be a bit of a struggle. Sadly enough there isn’t one perfect function to do this, but we can always try to make one.

Sorting an array will always use usort. Usort sends two values from the array (i.e. 1 and 2, 2 and 3, 3 and 4 etc.) to a user-defined function where you compare these two values:

usort($anarray, 'compareFunction');

There are two types of comparison, let’s start with binary safe string comparison (strcmp). This is perfect for strings, but not for integers or floating-point numbers bigger than 9. An array containing [5,33,4,6,9,11,24,3] will return:

Array ( [0] => 11 [1] => 24 [2] => 3 [3] => 33 [4] => 4 [5] => 5 [6] => 6 [7] => 9 )

The only way to fix this is to do a real numerical comparison with integers and floating-point numbers. So we have to split strings and numbers and end up like this:

function strcmpFn($r1, $r2) {
	$key = 'number';
	if(is_numeric($r1[$key]) && is_numeric($r2[$key])){
		return $r1[$key] - $r2[$key];
	}
	return strcmp($r1[$key],$r2[$key]);
}
$rows = array(
			array('number' => 5),
			array('number' => 33),
			array('number' => 4),
			array('number' => 6),
			array('number' => 9),
			array('number' => 11),
			array('number' => 24),
			array('number' => 3)
		);
usort($rows, 'strcmpFn');

print_r($rows);

This returns a nicely sorted array:

Array
(
    [0] => Array
        (
            [number] => 3
        )

    [1] => Array
        (
            [number] => 4
        )

    [2] => Array
        (
            [number] => 5
        )

    [3] => Array
        (
            [number] => 6
        )

    [4] => Array
        (
            [number] => 9
        )

    [5] => Array
        (
            [number] => 11
        )

    [6] => Array
        (
            [number] => 24
        )

    [7] => Array
        (
            [number] => 33
        )

)

You can also sort it descending by changing

	return $r1[$key] - $r2[$key];

to

	return 0 - $r1[$key] - $r2[$key];

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>