fightstarr20 fightstarr20 - 3 months ago 11
PHP Question

PHP sort array by filename

The code below scans through the current folder for word documents and then spits out an array of all it finds....

<?php
$a=array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.doc$/", $file))
$a[]=$file;
}

closedir($handle);

}
foreach($a as $i){
echo $i;
}
?>


This all works fine but the order is not what I want. Is there a way to sort the results by filename? I have looked at the sort function but cant figure out how to implement it in my situation.

Answer

You can use sort()

It operates in-place, so you don't get the sorted array as return value.

<?php
    $a=array();
    if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
    if(preg_match("/\.doc$/", $file)) 
    $a[]=$file;
    }

    closedir($handle);

    }
    sort($a);
    foreach($a as $i){
    echo $i;
    }
?>
Comments