How can I list all files in a directory sorted alphabetically using PHP?

后端 未结 7 861
终归单人心
终归单人心 2021-01-01 17:01

I\'m using the following PHP code to list all files and folders under the current directory:



        
7条回答
  •  -上瘾入骨i
    2021-01-01 17:35

    The manual clearly says that:

    readdir
    Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

    What you can do is store the files in an array, sort it and then print it's contents as:

    $files = array();
    $dir = opendir('.'); // open the cwd..also do an err check.
    while(false != ($file = readdir($dir))) {
            if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                    $files[] = $file; // put in array.
            }   
    }
    
    natsort($files); // sort.
    
    // print.
    foreach($files as $file) {
            echo("$file 
    \n"); }

提交回复
热议问题