sorting a scandir array with folders first using usort?

i’m making a basic directory listing script… so I use scandir, nothing fancy

$list = scandir($dir); usort($list,"cmp");

I’m wanting to use usort to sort the list so that folders come first… and I really have absolutely no idea what i’m doing with usort
I have this:

function cmp($a,$b) { if ($a == $b) { return 0; } elseif(is_dir($a)) return -1; else return 1; }

once again I have no clue what i’m doing. But the above code works - it sorts all the folders first and then files, but in some obscure order. nothing’s alphabetic or anything (the original array was), it just seems completely random… is there anyway I could use usort and still have them alphabetical?..thanks

You might want to check the conditions. In your function, no check is made for the sort order other than directory or not. The easy way to do what you need is to use strcmp() and return that value if both parameters $a and $b are both directories or files.

ah thanks, that’s what i needed. I changed my code to this

function cmp($a,$b) { if ($a == $b) { return 0; } elseif(is_dir($a) && is_dir($b)) return strcmp($a,$b); elseif(!is_dir($a) && !is_dir($b)) return strcmp($a,$b); elseif(is_dir($a)) return -1; else return 1; }

and it works fine but I really have no idea how to use usort, or if I coded that in the most effecient way, so is there a more convenient way of coding that?

What’s your problem with usort()?

This condition could be removed.

if ($a == $b) { return 0; }

The performance should not be an issue unless you have folders with thousands of entries, and even there, there won’t be much you can do without significant effort.

Sponsor our Newsletter | Privacy Policy | Terms of Service