Search code examples
phparraysdirectoryfilenamespreg-grep

How to build an indexed array of .html filenames that exist in a directory?


I am using this php code to get all html-files in the given directory:

$dirpath = ".....";
$filelist = preg_grep('~\.(html)$~', scandir($dirpath));

Now I want to get a specific element in the array, for example:

echo $filelist[0];

This fails. In my directory there are 52 files, and count($filelist) returns '52', but to get the first element I need to use echo $filelist[3]; The last item gets addresses by the index 54. What is this? Why do I can't adress them with index 0-51?

Edit: Possible duplicate only explains the shift of 2 indexes, what is the third? However: array_values solved the problem.


Solution

  • Use array_values() function to reset the numeric index to start from 0.

    Try:

    $dirpath = ".....";
    $filelist = array_values(preg_grep('~\.(html)$~', scandir($dirpath)));
    
    // print the first value
    echo $filelist[0];