Images filtered by array of filenames

Quick question.

Attempting to filter $page->images() against a custom structure field of image filenames.

For instance, I’d like to exclude all images except image-1.jpg and image-3.jpg, so that these are the only values present in the images() array of a given page.

Gallery:
- image-1.jpg
- image-2.jpg
- image-3.jpg

etc.

Have tried a number of things, eg. working with the filterBy(), but with no success so far. Have also tried with collections. Not sure how I should proceed.

Might be missing out on something completely obvious, but a nudge in the right direction would be great.

You can use $filter($callback): https://getkirby.com/docs/cheatsheet/files/filter

Thanks! Would that mean I can use it something like this?

$filenames = $page->gallery()->toStructure();

$images = $page->images()->filter(function($image) {
	return $image == $filenames;
});

You need an array of filenames and then check if the image filename is in the array. Also, you want to exclude the image from the array, don’t you?

$filenames = $page->gallery()->yaml(); //you need a simple array here, I don't know what `yaml()` gives you here, depends on your field.

$images = $page->images()->filter(function($image) {
	return !in_array($image->filename(), $filenames);
});

Wouldn’t it make more sense to only include the desired images in the gallery field?

1 Like

Hmm, yes I see what you mean.
Sorry, maybe I was unclear, not trying to exclude from the gallery field itself. Just select images from $page->images() if they exist in the gallery field.

$filenames = $page->gallery()->yaml();

$images = $page->images()->filter(function($image) {
	return in_array($image->filename(), $filenames);
});

Gives me an error: in_array() expects parameter 2 to be array, null given with print_r($filenames) giving me:

Array ( [0] => image-1.jpg [1] => image-2.jpg)

With the field containing:

Gallery:
- image-1.jpg
- image-2.jpg

That’s easier:

<?php
$filenames = $page->gallery()->yaml();
foreach($filenames as $filename):
  if($image = $page->image($filename): ?>
  <img src="<?= $image->url() ?> alt="">
  <?php endif ?>
<?php endforeach ?>
1 Like

Forgot. Thanks for marking as solved!