The issue is here: return($directorylist); sort($directorylist); PHP: Your returning the data before its sorted, so your returning the unsorted data!, to resolve return the data aftet being sorted, as follows: <?php function folderlist(){ $startdir = './'; $ignoredDirectory[] = '.'; $ignoredDirectory[] = '..'; if (is_dir($startdir)){ if ($dh = opendir($startdir)){ while (($folder = readdir($dh)) !== false){ if (!(array_search($folder,$ignoredDirectory) > -1)){ if (filetype($startdir . $folder) == "dir"){ $directorylist[$startdir . $folder]['name'] = $folder; $directorylist[$startdir . $folder]['path'] = $startdir; } } } closedir($dh); } } sort($directorylist); return($directorylist); } $folders = folderlist(); foreach ($folders as $folder){ $path = $folder['path']; $name = $folder['name']; echo '<a href="'. $path . $name .'">' . $name . '</a><br />'; } ?> PHP: