1

Why is this only returning one file?

    $iterator = new FilesystemIterator($absoluteDirectoryPath);
    $regexIterator = new RegexIterator($iterator, $filter);
var_dump($regexIterator);

I just need a list of files and I can't see anywhere why this would be returning only one file. Heres the output:

RegexIterator {#7 ▼
  +replacement: null
  innerIterator: RecursiveIteratorIterator {#5 ▼
    innerIterator: RecursiveDirectoryIterator {#4 ▼
      path: "/home/**/**/**/**/**/**/**/home"
      filename: "home.php"
      basename: "home.php"
      pathname: "/home/**/**/**/**/**/**/**/**/home.php"

I've blanked out the path of course. But theres only one entry, home.php, when theres at 4 files in this directory.

Chud37
  • 4,907
  • 13
  • 64
  • 116
  • Please [edit] your question to include the full source code you have as a [mcve], which can be tested by others. – Progman Feb 12 '21 at 17:37
  • @Progman thats really it. I put a var_dump in there but there is no extra code, I am only getting one entry in the output. – Chud37 Feb 12 '21 at 19:17

1 Answers1

1

An iterator by definition points to one element. You have to iterate over all elements and store them in a container. You can use iterator_to_array for this:

$iterator = new FilesystemIterator($absoluteDirectoryPath);
$regexIterator = new RegexIterator($iterator, $filter);
var_dump(iterator_to_array($regexIterator));

or you can use a foreach loop to iterate over all elements and dump each element.

Here you can read more about iterators.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • Thanks, But why doesnt literally any other example I see show this? They directly have a `foreach` after the RegexIterator and can access the files straight away, which I cant. See this example: https://stackoverflow.com/a/9749009/1445985 – Chud37 Feb 12 '21 at 19:34
  • @Chud37 The iterator returns the data when you request them via the methods provided by the iterator. You can get the values by using a `foreach` loop as seen in the linked question. – Progman Feb 12 '21 at 19:46
  • @Program, yes, But I do that and I get undefined. I've created a new question because I feel i've worded this one wrong. – Chud37 Feb 12 '21 at 19:51
  • 1
    @Chud37 A `foreach` loop uses iterators to iterate over a container. As I wrote in my answer you can use `iterator_to_array`, a `foreach` loop or another way to iterate over the container. – Thomas Sablik Feb 12 '21 at 19:57