views:

40

answers:

1

Perhaps I'm doing something embarrassingly wrong, but why isn't this array being sorted?

$narray=array();

$dir_handle = @opendir($path.$projectFolder) or die("Unable to open $path$projectFolder");

$i=0;

while($file = readdir($dir_handle)) {

 $filenameSplit = explode('.',$file);

 if ($file != "." && $file != ".." && $filenameSplit[0] != "logo" && $filenameSplit[1] != "zip" && $filenameSplit[1] != "pdf" && $filenameSplit[1] != "doc" && $filenameSplit[1] != "psd" && $filenameSplit[1] != "") {

  $narray[$i]=$file;

  $i++;
 }

}

natcasesort($narray);

I seem to be getting the same results I get when I don't attempt to sort the array at all. sort() works, but nothing else seems to.

Thanks for any help!


Update:

Here are sample results:

With no sort:

03_piper_file-manager_02.jpg
05_piper_login-page_02.jpg
02_piper_file-manager_no-slides_01.jpg
04_piper_file-manager_02.jpg
01_piper_file-manager_no-slides_01.jpg

With sort():

01_piper_file-manager_no-slides_01.jpg
02_piper_file-manager_no-slides_01.jpg
03_piper_file-manager_02.jpg
04_piper_file-manager_02.jpg
05_piper_login-page_02.jpg

With natsort() or natcasesort():

03_piper_file-manager_02.jpg
05_piper_login-page_02.jpg
02_piper_file-manager_no-slides_01.jpg
04_piper_file-manager_02.jpg
01_piper_file-manager_no-slides_01.jpg

I expect at the very least for natsort's results to look like sort's.

+2  A: 

natcasesort maintains the key/value relationship, so if you are iterating over the array with an index, you will see this behavior.

Try print_r($narray) after natcasesort. You can iterate the array using foreach.

foreach ($narray as $elem)
{
   /* operate on $elem */
}
Brandon Horsley
`print_r` after `natcasesort` gives me this:`Array ( [4] => 01_piper_file-manager_no-slides_01.jpg [2] => 02_piper_file-manager_no-slides_01.jpg [0] => 03_piper_file-manager_02.jpg [3] => 04_piper_file-manager_02.jpg [1] => 05_piper_login-page_02.jpg` I'm not experienced enough to know what to make of it, unfortunately.
Tim
+1 Nice psychic debugging.
Artefacto
@Tim Call `array_values` before iterating or iterate with `foreach` instead.
Artefacto
I updated my answer to tell you how to iterate over the array in order.
Brandon Horsley
I have a for loop that looks like this:`for($i=0; $i<sizeof($narray); $i++)`
Tim
@Tim: Change that for loop to the foreach listed in my answer, and use "$elem" instead of "$narray[$i]" - you will be set.
Brandon Horsley
ah ok, I will try it. Thanks!
Tim
@Tim: A plain for loop will not access the elements in order as they are in the array. It will access them by the value of the key (i.e. in their original order).
Felix Kling
Awesome, it's working. Thanks so much!
Tim
@felix exactly, that was my problem.
Tim