How to store all result from a loop and each result separated by a comma?

74 views Asked by At

Currently I have this working PHP code for search photos inside a folder by name:

$dirname = "photos";
$filenames = glob("$dirname/*{380,381,382,383,384,385}*", GLOB_BRACE);

foreach ($filenames as $filename) {
    echo $filename . "<br>";
}

I have typed manualy those numbers 380,381,382,383,384,385 and I would like to have them typed exactly the same but automatically.

If I'm not wrong we have to do an array() on this code:

$start = 380;
$end = 385;

for($i = $start; $i <= $end; $i++) {
    echo "$i<br>";
}

I haven't found how to store the whole loop inside a variable for reproduce the same result as the first code but automatically.

2

There are 2 answers

0
Rizier123 On BEST ANSWER

This should work for you:

Just use range() to create the array with the numbers, which you then can implode() into a string, e.g.

$filenames = glob("$dirname/*{" . implode(",", range(308, 385)) . "}*", GLOB_BRACE);
0
Moritz On
$array = range(380, 385);
$string = '{' . implode(',', $array) . '}';