Limit of items in the "foreach"

2

I have a code that takes the images from the images/FotosdoWhatsAPP folder, but it is displaying all the images, I would like to display only a quantity X (eg 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>*/
}

?>
    
asked by anonymous 20.11.2018 / 23:38

2 answers

5

It has some form:

Do not use foreach , use 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 a counter and put a condition (I think 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 in the array key (I find it 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.'">
    
20.11.2018 / 23:46
3

An alternative is to apply the classes DirectoryIterator and LimitIterator :

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

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

But obviously the complexity of this to replace a mere if usually makes the solution unfeasible. It is also at your discretion to adapt the use of DirectoryIterator , or analog, to select only the desired files.

    
20.11.2018 / 23:53