How can arrays be effectively used in the scan_dir function in PHP to sort file listings?

To effectively use arrays in the scan_dir function in PHP to sort file listings, we can use the scandir function to get the list of files in a directory and then sort the array using functions like sort() or natcasesort(). This will allow us to organize the file listings in a desired order, such as alphabetically or numerically.

function scan_dir($dir){
    $files = scandir($dir);
    // Remove . and .. from the array
    $files = array_diff($files, array('.', '..'));
    
    // Sort the array alphabetically
    sort($files);
    
    foreach($files as $file){
        echo $file . "<br>";
    }
}

// Usage
scan_dir("path/to/directory");