Natural Order Sorting through PHP

Standard

Most of us while coding, come across with various “sorting“. It’s a natural requirement that a list should be sortable or sorted, whatever it might be. The most common sorting is sorting of numbers, sorting of alphabets etc. That’s easy! Correct? Ok, now if you have a list of alpha-numeric characters, what will happen to the sorting?

See the example. I have a list (in the form of an PHP array) as follows:

Orange 12
Orange 10
Orange 2
Orange 1

When you sort the list using asort(), the output you will get is the following:

Orange 1
Orange 10
Orange 12
Orange 2

As you can see from the output that the order is not correct as per the human understanding. Per human understanding the order should read as follows:

Orange 1
Orange 2
Orange 10
Orange 12

So, how to do that? It’s simple and natsort() will do that for you. Here is a sample code for the same.

<?php
$array = array('Orange 12', 'Orange 10', 'Orange 2', 'Orange 1');
print_r(asort($array)); // regular sorting
print_r(natsort($array)); // natural order sorting
?>

Run the code above and see the difference in the output.

Enjoy coding in PHP!

Advertisements

I will be happy to answer your queries

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s