Search code examples
phpscandir

scandir - how to get original folders - files order


items inside fs folder:

lorem  
ipsum  
sun  
moon.php  

function get_items($path){
    $arr = scandir($path);
    $arr = array_slice($arr, 2);
    foreach($arr as $el){
        if(is_dir($el)){
            echo "<div class='folder'>" . $el . "</div>\n";
        }
        else{
            echo "<div class='file'>" . $el . "</div>\n";
        }
    }
}

Result - all items are echoed as class - file and in the following order:

ipsum  
lorem  
moon.php  
sun 

How to get folders as folder and in original order - first folders and then files ?

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum


Solution

  • The code you posted may have issues because scandir return just the name of files and folders, not their absolute path.

    When you later use is_dir you pass just the file/folder name (a relative path). When doing so, according to the documentation

    If filename is a relative filename, it will be checked relative to the current working directory.


    You can fix your code by passing a correct path to is_dir

    is_dir("$path/$el")

    In order for this solution to work $path must not have the trailing slash (because we do add it).

    Furthermore $path must be either an absolute path to the target directory or a path to the target directory relative to the working directory the script is run.


    Finally to list folders first then files you may sort the array or, more simply, make two foreach loops as follows:

    function get_items($path){
        $arr = scandir($path);
        $arr = array_slice($arr, 2);
    
        sort($arr);
    
        // Folders first
        foreach($arr as $el){
            if(is_dir("$path/$el")){
                echo "<div class='folder'>" . $el . "</div>\n";
            }
        }
    
        // Then files
        foreach($arr as $el){
            if( ! is_dir("$path/$el")){
                echo "<div class='file'>" . $el . "</div>\n";
            }
        }
    }