如何将目录中的文件名存储在数组php中


How to store file names from directory in array php

我有一个目录,里面有两个文件,我想把文件名存储到数组中,当我打开目录和托盘来存储文件名时,我得到了两个数组,一个[0]=>may.log,另一个[0]=>may.log,[1]=>april.log。这是我的代码:

    <?php       
        $dir = 'data';
        $fileNames = array();
        if(is_dir($dir)){
            $handle = opendir($dir);
            while(false !== ($file = readdir($handle))){
                if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
                        $fileNames[] = $file;
                        $fileNames = array_reverse($fileNames);
                        print_r($fileNames);
                }
            }
            closedir($handle);
        }else {
            echo "<p>There is an directory read issue</p>";
        }
    ?>
  1. 从循环中移出array_reverseprint_r

    $dir = 'data';
    $fileNames = array();
    if(is_dir($dir)){
        $handle = opendir($dir);
        while(false !== ($file = readdir($handle))){
            if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
                    $fileNames[] = $file;
            }
        }
        closedir($handle);
        $fileNames = array_reverse($fileNames);
        print_r($fileNames);
    }else {
        echo "<p>There is an directory read issue</p>";
    }
    
  2. 将此代码替换为glob(如@Rizier所说)