twan twan - 1 year ago 86
PHP Question

Natsort not working as it should

I got a script that shows a gallery, the images in the gallery are pulled from a directory using scandir (a function). I'm using natsort to order the images in a numerical way (all images only have numbers, example: 1.jpg 12.jpg 13.jpg etc etc).

Natsort should order them but instead the images are not sorted at all.

My code:

function scan_dir($dir) {
$ignored = array('.', '..', '.svn', '.htaccess','index.html');

$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$files[$file] = filemtime($dir . '/' . $file);

$files = array_keys($files);

return ($files) ? $files : false;
if(is_dir($_SERVER['DOCUMENT_ROOT'].'/_intern/SNM/cms/images/Projecten/'.$contentcr[0]['alias'].'/') != FALSE){
foreach(scan_dir($_SERVER['DOCUMENT_ROOT'].'/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/') as $entry) {
$gallery .= '
<a href="/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/'.$entry.'">
<img class="galleryimgs" title="'.$contentcr[0]['alias'].'" alt="'.$contentcr[0]['alias'].'" src="/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/'.$entry.'" />
echo '';
echo $gallery;

Answer Source

Short answer is:

natsort($files) sorts by value, not by key. It is in reality equivalent to sort($files,SORT_NATURAL)

If you want to sort keys (which is what you need in your case) you need to use:


A full list of PHP sort functions can be found in the manual pages at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download