Array Sorting

I came across this problem recently:

How would you sort an array of strings to their natural case-insensitive order, while maintaining their original index association?

array(
	'0' => 'z1',
	'1' => 'Z10',
	'2' => 'z12',
	'3' => 'Z2',
	'4' => 'z3',
)

The end goal is this:

array(
	'0' => 'z1',
	'3' => 'Z2',
	'4' => 'z3',
	'1' => 'Z10',
	'2' => 'z12',
)

It’s done like this:

asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)

Without any flags, asort($arr) will sort alphabetically, but won’t apply natural sort order, nor will it ignore case.

Natural sort order will treat z3 as less than z12 because it looks at the numbers like humans do. The default is alphabetic sorting, which would put z12 before z3 because the 1 is less than the 3.

The case sensitivity, which is the default setting, would cause the lower case z to come before the uppercase Z.

So, by applying SORT_STRING all the items will be treated as strings, and then the SORT_FLAG_CASE makes it case insensitive, and SORT_NATURAL puts the numbers in the order we humans prefer to sort by.

Leave a Reply

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