Skipping duplicated images in a foreach loop

Hello,
I’m pulling all the images from all the children pages of a page using a foreach loop.
A same image might be used several times across those children pages.

Is there a way I can skip if an image is repeated and only show all the images once?
Can this perhaps be accomplished via ->filterBy('filename', '*=', '...')?

What I need is to basically tell Kirby to skip duplicated image files.

Thanks a lot, again.

<?php 
$filenames = [];
foreach( $page->children()->listed()->images() as $image) {
    if(in_array($image->filename(), $filenames)) { continue; }
    $filenames[] = $image->filename();
    echo $image;
} 

Thanks for the reply!
Could this be applied when trying to do that by getting all the layout blocks from the subpages?

 <?php foreach ($page->parent()->children()->listed() as $subpage): ?>

    <?php foreach ($subpage->layout()->toBlocks()->filterBy('type','image') as $block): ?>
      <?php if($block->image()->isNotEmpty()): ?>

      <div class="img">
          <?php if($thumb = $block->image()->toFile()): ?>
            <img class="image" src="<?= $thumb->resize(800)->url() ?>">
          <?php endif ?>
      </div>

        <?php endif ?>
      <?php endforeach ?>

 <?php endforeach ?>

Yes (note that I changed the position of the if statement to prevent an empty div in case the image doesn’t exist and remove an unnecessary if statement (checking if the image field is empty is not necessary, because you also check for an image object and you won’t have one if the field is empty)

 <?php 
$filenames = [];
foreach ($page->parent()->children()->listed() as $subpage): ?>
  <?php foreach ($subpage->layout()->toBlocks()->filterBy('type','image') as $block): ?>
      <?php if(($thumb = $block->image()->toFile()) && ! in_array($thumb->filename(), $filenames)): ?>
        <?php $filenames[] = $image->filename(); ?>
        <div class="img">
          <img class="image" src="<?= $thumb->resize(800)->url() ?>">
        </div>
      <?php endif ?>
  <?php endforeach ?>
<?php endforeach ?>
1 Like

Thanks for this.
I’m getting this error Undefined variable: thumb when applying this snippet.

I forget the parenthesis around $thumb = $block->image()->toFile(), corrected above, please try again.

Thanks a lot.
I needed to change <?php $filenames[] = $image->filename(); ?> for <?php $filenames[] = $thumb->filename(); ?> in order to make this work.

After that, working like a charm.
I really appreciate the help!