Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array case-insensitive key sort in PHP version 5.3 or less

PHP 5.4 introduces the useful SORT_FLAG_CASE for making any other search case insensitive. Unfortunately this isn't available in PHP 5.3 or less and so I was wondering how the following array:

array('a'=>2,'b'=>4,'A'=>1,'B'=>3);

Could be sorted into:

array('A'=>1,'a'=>2,'B'=>3,'b'=>4);

As the usual ksort() function sorts it as:

array('A'=>1,'B'=>3,'a'=>2,'b'=>4);
like image 363
M1ke Avatar asked Aug 29 '12 14:08

M1ke


People also ask

Are PHP array keys case-sensitive?

Yep, array keys are case sensitive.

How do you sort a key value array?

There are four functions for associative arrays — you either array sort PHP by key or by value. To PHP sort array by key, you should use ksort() (for ascending order) or krsort() (for descending order). To PHP sort array by value, you will need functions asort() and arsort() (for ascending and descending orders).

What is Rsort PHP?

The rsort() function sorts an indexed array in descending order. Tip: Use the sort() function to sort an indexed array in ascending order.


1 Answers

A comment on one of the PHP function reference pages pointed me to the uksort() function; this (and the uasort() function for sorting by value instead of key) allow the comparison algorithm for shifting in the quick sort to be written by the user.

Combine this with the very simple strcasecmp() function (which compares two strings and returns <0 for a>b and >0 for a>b) gives you:

uksort($array, 'strcasecmp');

To easily achieve the effect of:

ksort($array,SORT_STRING | SORT_FLAG_CASE);

In PHP 5.3 or less.

like image 122
M1ke Avatar answered Oct 03 '22 04:10

M1ke