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

192 views Asked by At

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.

4

There are 4 answers

0
Madhur Bhaiya On BEST ANSWER

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];
1
Saurabh Sharma On

Those are the current (.) and parent (..) directories. They are present in all directories, and are used to refer to the directory itself and its direct parent.
Why is it whenever I use scandir() I receive periods at the beginning of the array?

0
Mohd Abdul Mujib On

Just use

$filelist = array_values($filelist);

Your function is cherry picking the items from an already indexed array, so the keys are not in sequence.

0
mickmackusa On

Using scandir() then applying a regex filter, then re-indexing is an inefficient approach, when glob() can deliver what you want in one call.

The following will generate an array of only .html files.

If you want to see the dirpath prepended to the filename:

$filelist = glob($dirpath . "*.html");  // you may need to add a slash before the filename

If you want to see only the filenames:

chdir($dirpath);
$filelist = glob("*.html");