Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array items in PHP so that it is not case sensitive to letters

When I use sort($topics) I get something along the lines of:

  1. Apple
  2. Green
  3. Zebra
  4. grass

In this example, "grass" starts with a lower case g but ends up after "Zebra" which has a capital letter.

How do I make it so that it sorts it where it ignores whether the word starts with capitals or not?

  1. Apple
  2. Green
  3. grass
  4. Zebra
like image 421
Simon Suh Avatar asked Oct 14 '11 06:10

Simon Suh


People also ask

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

The natcasesort() function sorts an array by using a "natural order" algorithm. The values keep their original keys.

How do you sort an array of objects in PHP?

Approach: The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.


1 Answers

Call usort() as usort($topics, 'strnatcasecmp').

strcasecmp would do the job, too, but strnatcasecmp will also sort properly when you have numbers in your string.

like image 66
ThiefMaster Avatar answered Sep 30 '22 06:09

ThiefMaster