case insensitive sort()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

case insensitive sort()

Post by Luke »

Is there any case-insensitive way to sort arrays? I keep getting this order with sort()
Tyson
Willy
Zoology
luke
mc2
oggy
test
User avatar
TheMoose
Forum Contributor
Posts: 351
Joined: Tue May 23, 2006 10:42 am

Post by TheMoose »

You can define your own sort function by doing:

Code: Select all

function mysort($a, $b) {
	return strcmp(strtolower($a), strtolower($b));
}

usort($myarray, "mysort");
Last edited by TheMoose on Wed Jun 14, 2006 5:30 pm, edited 2 times in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

natcasesort(), or shockers of shockers: usort()
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

feyd wrote:natcasesort(), or shockers of shockers: usort()
I have tried both of them and still come up with:

Code: Select all

function mysort($a, $b) {
        return strcmp(strtolower($a), strtolower($b));
	}
	
	usort($directories, "mysort");

/* Both give me this:
This is a folder
Zoology
luke
mc2
test*/
Let me look at the rest of my code and see if maybe it is getting resorted somewhere else or something.... this is driving me crazy!

EDIT: nope... I print_r'd the array RIGHT after I did the compare and still get the wrong order... hmm...

EDIT AGAIN: OK geeze!! i finally found out that there were some arrays in my array (that i didn't even notice when I print_r'd) that were throwing things off... I need more coffee I guess.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

How about:

Code: Select all

usort($directories, 'strcasecmp');
(#10850)
Post Reply