When sorting array items in PHP, 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, consider the following example:

$scores = array(

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

There’s a simple way to fix this. We need to augment the usort() function by adding an extra argument. We’ll add the SORT_NUMERIC predefined constant as the second argument and this will instruct PHP to ignore sorting on the string segment of the array values and instead successfully sort the array by the ID only.

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

usort($scores, SORT_NUMERIC);

//0 = 28-Joe
//1 = 32-Andy
//2 = 43-Steve