Sorting Alphanumeric Data in PHP

Author - Kritika Sood

While fetching data from database, in SQL query I had ‘order by’ clause but the results were not sorted when the data was in alphanumeric form. The reason for this is that SQL sorts character by character from left to right. So it places c10 before c2 as 1<2.

For Example:

$query="select id,shortname from {abc} where rollno=".$id." GROUP BY shortname ORDER BY shortname ASC";

$query= $DB->get_records_sql($query);

foreach($query as $a)
{
array_push ($names,$a->shortname);   
}
echo"<pre>";print_r($names);echo"<pre>";

Output:

   [0] => c1
   [1] => c10
   [2] => c2
   [3] => c3
   [4] => c4
   [5] => c5
   [6] => c6
   [7] => c7
   [8] => c8
   [9] => c9

Solution: natcasesort($names)

natcasesort() uses natural sorting algorithm in the way human being sorts data.

Output:

   [0] => c1
   [2] => c2
   [3] => c3
   [4] => c4
   [5] => c5
   [6] => c6
   [7] => c7
   [8] => c8
   [9] => c9
   [1] => c10

Note: Index of array after sorting gets unsorted when we use natcasesort().

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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