Ben Viatte
Ben Viatte

Reputation: 503

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

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?

Upvotes: 0

Views: 160

Answers (1)

trincot
trincot

Reputation: 350212

You could use array_slice:

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

Upvotes: 1

Related Questions