Item limit in "foreach"

Asked

Viewed 574 times

2

I have a code that picks up the images from the folder images/FotosdoWhatsAPP, but is displaying all images, would like to display only a quantity X (ex: 5 images).

<?php  
$dirname = "images/FotosWhatsApp/";
$images = glob($dirname."*.{jpg,jpeg,png,gif,JPG,PNG,JPEG,GIF}",GLOB_BRACE);

foreach($images as $image) {
    echo '
<a href="'.$image.'" data-at-1920="'.$image.'">
<div class="div-thumbnail-portfolio" style="background-image: url('.$image.');background-repeat: no-repeat;background-size: cover; background-position: center center; " class="thumbnail-detalhe">

</div>
</a>
    ';

    /*<a href="'.$image.'" rel="gallery" class="fresco" data-fresco-group="example">
    <img src="'.$image.'" style="background-image: url('.$image.');background-repeat: no-repeat;background-size: cover; background-position: center center; " class="thumbnail-detalhe"/>
</a>*/
}

?>

2 answers

5


Has some form:

Don’t use the foreach, use the for:

$images = glob($dirname."*.{jpg,jpeg,png,gif,JPG,PNG,JPEG,GIF}",GLOB_BRACE);
for ($i = 0; count($images); $i++) {
    echo '
<a href="'.$images[i].'" data-at-1920="'.$images[i].'">

Create an accountant and put a condition (I find inefficient and ugly):

$images = glob($dirname."*.{jpg,jpeg,png,gif,JPG,PNG,JPEG,GIF}",GLOB_BRACE);
$i = 0;
foreach($images as $image) {
    echo '
<a href="'.$image.'" data-at-1920="'.$image.'">
...
if (++$i > 4) break;

Use a condition on the key array (I find inefficient and ugly):

$images = glob($dirname."*.{jpg,jpeg,png,gif,JPG,PNG,JPEG,GIF}",GLOB_BRACE);
foreach($images as $key => $image) {
    echo '
<a href="'.$image.'" data-at-1920="'.$image.'">
...
if ($key > 4) break;

Limit the array before entering the loop (compensates in some cases):

$images = array_slice(glob($dirname."*.{jpg,jpeg,png,gif,JPG,PNG,JPEG,GIF}",GLOB_BRACE), 4);
foreach($images as $image) {
    echo '
<a href="'.$image.'" data-at-1920="'.$image.'">

I put in the Github for future reference.

3

An alternative is to apply together the classes DirectoryIterator and LimitIterator:

$directory = new DirectoryIterator('./data');
$firstFiveFiles = new LimitIterator($directory, 0, 5);

foreach ($firstFiveFiles as $file) {
    ...
}

But obviously the complexity of it to replace a mere if usually disable the solution. It is up to you also adapt the use of DirectoryIterator, or analog, to select only the desired files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.