Home > Enterprise >  Foreach loop to only cycle through specific range of files (php)
Foreach loop to only cycle through specific range of files (php)

Time:07-30

I have a list of html files in a directory:

1-foo.html
2-bar.html
3-foo.html
4-bar.html
5-foo.html
...

If I want to display just the 3 first ones with a foreach loop in PHP, I can do this:

<?php
$i = 0;
foreach (glob("*.html") as $filename)
{
  include $filename;
  if (  $i == 3) break;
}
?>

But what if I want to display just the 3 next ones? I'd need a foreach loop that runs a specific number of times, like above, but I'd need that loop to start at position 4, instead of 1.

Can anyone think of a way to do that with foreach?

CodePudding user response:

You could use array_slice:

foreach (array_slice(glob("*.html"), 3, 3) as $filename)
{
  include $filename;
}
  • Related