- iPhone (2)
- Learning (42)
- Linux (4)
- Debian (1)
- Mac Terminal / Linux (5)
- Other Stuff (1)
- Programming (66)
- Slim Framework (1)
- Uncategorized (4)
- WordPress (5)
We participate in the Amazon Service LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
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:
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.