Knowband Blog | Ecommerce Modules

Case-insensitive array sorting in the Php

Problem:

$data = array(“A”,”M”,”X”,”b”,”d”,”E”,”l”);

I need to sort the data base on value. When I use asort($data), got the following:

[0] => A
[5] => E
[1] => M
[2] => X
[3] => b
[4] => d
[6] => l

In the above example, “b”,”d” and “l” starts with a lower case but ends after “X” which has an upper case.

How can we sorts it where it ignores whether the words start with upper case or lower case?

I was expecting this

[0] => A
[3] => b
[4] => d
[5] => E
[6] => l
[1] => M
[2] => X

Solution:

Use natcasesort($data); and you will get the exact same result.

Notes:

We can use this function to sort our arrays using a case insensitive “natural array” algorithm. natcasesort() is a case insensitive version of the natsort().

Syntax:

bool natcasesort ( array &$array );

Returns

Returns true in case of success and false for failure.

To know more about natural array” algorithm or natcasesort() : https://www.w3schools.com/php/func_array_natcasesort.asp