Sometimes you'll want to sort an array by its values. Normally you can use one of the PHP sort functions such as sort() or usort(). This will sort your array into ascending order for either integer, starting with zero or string, from A - Z.

However, you may have the following array:

 
$scores = array(
    '32-Andy',
    '43-Steve',
    '28-Joe'
);

If you try to sort these by the ID (28, 32, 48) the sort function will not take just the numbers into account. It will also then sort on the string, from A to Z.

There's a simple way to fix this. We need to upgrade the usort() function by adding an extra argument. We'll add the SORTNUMERIC predefined constant as the second argument and magically PHP will ignore sorting on the string part of the array values and instead successfully sort the array by the ID.

Using the following code will output the array in the order: 2, 0, 1 as expected.

usort($scores, SORTNUMERIC);
print_r($scores);
//0 = 28-Joe
//1 = 32-Andy
//2 = 43-Steve