1

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Ccenter
  • 107
  • 10
  • Possible duplicate of [Why is it whenever I use scandir() I receive periods at the beginning of the array?](https://stackoverflow.com/questions/7132399/why-is-it-whenever-i-use-scandir-i-receive-periods-at-the-beginning-of-the-arr) – Saurabh Sharma Oct 13 '18 at 07:52
  • `$filelist = array_values(array_diff(scandir($dirpath), ['.','..']));` For [Example](http://sandbox.onlinephpfunctions.com/code/3ab1f6ed317cf4ce9cf277c234c50ff86f8b8fd8) It's probably a bad practice to mix file types in the same Dir, such as `.html` and `.css` in the same place. – ArtisticPhoenix Oct 13 '18 at 08:39
  • @ArtisticPhoenix `glob()` is the one-call solution. – mickmackusa Oct 13 '18 at 13:19
  • @mickmackusa - I know what it is ... but strangely I never used it before. I don't use scandir much (not in the last 5 years). Mainly I use SPL classes. – ArtisticPhoenix Oct 13 '18 at 18:56

4 Answers4

4

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];
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
1

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?

Saurabh Sharma
  • 430
  • 2
  • 11
1

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.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
0

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");
mickmackusa
  • 43,625
  • 12
  • 83
  • 136