0

How can I load multiple vars each containing a single path into an array variable?

$dir1 = "/path/1/";
$dir2 = "/path/2/";
$dir3 = array($dir1, $dir2);

$directories = array($dir3);
$count = 0;
foreach ($directories as $dir) {
    $files = glob("{$dir}*.gz") ?: array();
    $count += count($files);
}

When I print $dir3 I get both paths as an array but I cannot get the $dir3 var for $directories to work. I have tried looking for answers but I am unable to find similar use cases. The documentation on php.net is also unclear to me. I'm still new to PHP and programming in general.

I want to figure out how I can have multiple paths in a single var but still have foreach execute on each path in the var.

5
  • 2
    Why not directly foreach on $dir3? Right now you're making it an array of arrays with array($dir3). Commented Aug 31, 2020 at 8:58
  • No need for a loop. Glob is capable of using multiple directories at once separated by comma. Commented Aug 31, 2020 at 9:05
  • 1
    @Jeto Thanks! That replaced $directories with $dir3 worked. Can you mark this as the answer? Commented Sep 1, 2020 at 2:43
  • @MarkusZeller I tried glob("{$dir3}") but that doesn't seem to work. What would be the correct way to use it? Tried multiple vars with a single path as well but no luck (eg: $dir1,$dir2) Commented Sep 1, 2020 at 2:45
  • Look at GLOB_BRACE option. Commented Sep 1, 2020 at 6:24

1 Answer 1

2

$dir3 already is an array containing your directories.

By doing $directories = array($dir3);, you're therefore creating an array of arrays.

So you could simply replace your code with:

$dir1 = "/path/1/";
$dir2 = "/path/2/";

$directories = array($dir1, $dir2);  // or $directories = [$dir1, $dir2];

$count = 0;
foreach ($directories as $dir) {
    $files = glob("{$dir}*.gz");
    $count += count($files);
}

However, as @MarkusZeller has pointed out, you can also pass a comma separated list of directories directly to glob, using the GLOB_BRACE flag:

$dir1 = "/path/1/";
$dir2 = "/path/2/";

$commaSeparatedDirectories = implode(',', [$dir1, $dir2]);

$count = count(glob("{{$commaSeparatedDirectories}}*.gz", GLOB_BRACE));
Sign up to request clarification or add additional context in comments.

1 Comment

Looks much cleaner using GLOB_BRACE. Thanks for putting my suggestion in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.