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

Sunny Saurabh

Sunny Saurabh

Sunny Saurabh is an experienced Software engineer in C# and ASP.NET as well as an expert as a PHP developer. He has also expert in database design, server maintenance and security. He has achieved this goal only in the short span of 3yrs and still looking forward to achieving more in the IT industry. He lives in New Delhi and his hobby to write the technical writeups.

Leave a Reply

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