PHP Sort not working as intended

Here is my code:

<?php

	$search = $_SERVER['DOCUMENT_ROOT'] . '/data/';
	$folders = str_replace($search, '', glob($search . '*', GLOB_ONLYDIR));
	$filesExt = str_replace($search, '', glob($search . '*.[dDxXpPtT][oOlLpPdDxX][cCsStTfF]'));
	$filesExtx = str_replace($search, '', glob($search . '*.[dDxXpP][oOlLpP][cCsStT][xX]'));
	$files = array_merge($filesExt, $filesExtx);
	sort($files);
	
	foreach ($files as $file) {
		echo $file . '<br />';
	}

?>

What is does is grab a listing of certain file types and directories in a path.

Then, I am trying to sort the $files array alphabetically but the output is this:

Book1.xls
Book1.xlsx
Book2.xlsx
Book3.xlsx
aBook1 - Copy (3).xlsx
apple.doc
links - Copy (2).txt
links - Copy.txt
links.txt
test.doc
test.docx

What am I doing wrong?

Fixed.

I ended up using natcasesort

Err, I need some help with this again.

I have a list of example file names here:


g.doc
a.doc
1.doc
http://example.com/test1/r.doc
http://example.com/test2/b.doc

I want to sort this array alphabetically with the basename of the file but I want to keep the entire link. Using natcasesort it will sort the links with the http… in it.

I’ve tried natcasesort(basename($var)); but this doesn’t seem to work.

I can’t use substr because the size of the link and file names change.

Anyone have any ideas? I need to keep the link part because I need to link it later on and the paths aren’t constant.

You can sort with ‘usort’.
‘usort’ will sort your file according to a user defined function.
For example:

  1. The sort function

function cmp($a, $b){
  if (basename($a)==basename($b))
    return 0;
  else
   return basename($a)<basename($b)?-1:1;
}

  1. The call to ‘usort’:
usort($my_arr, 'cmp');

Ah, that might be better than what I was doing. I had worked around the issue by putting the URL in the key of the array and the basename of the file as the value for that key.

It would probably be wiser to use (only) strnatcasecmp() within your cmp() function. It would behave more like Ryan wants, and saves you (needlessly) trying too hard to return -1, 0 or 1. :eye: