Shuffle until first image satisfies condition

Hi!

I have a simple image slideshow with landscape and portrait images. I want this slideshow to be randomized every time, so I have a shuffled loop of all the files from a project page, but I want the first image to always be a landscape image. How would I achieve shuffling a loop until the first image satisfies this condition?

Thank you!

The easiest way is probably to get the first landscape image first. Then the rest of the images .

$firstImage = $page->images()->filterBy('isLandscape', true)->shuffle()->first();
$otherImages = $page->images()->not($firstImage)->shuffle();

Then you render the first image first, followed by the loop for the other images. An alternative would be to get the first image and prepend it to the other images, then loop through all.

Assuming your markup is some sort of list

<?php if($page->images()->count()): ?>
  <ul>
    <?php if($firstImage): ?>
      <li><img src="<?= $firstImage->url() ?>"></li>
    <?php endif ?>
    <?php foreach($otherImages as $img): ?>
      <li><img src="<?= $img->url() ?>"></li>
    <?php endforeach ?>
  </ul>
<?php endif ?>

Typo alert : the second variable’s name should be $otherImages and not $other Images :wink:

1 Like

Thank you, @manuelmoreale, my keyboard in conjunction with autocorrection is driving me crazy…

I hear you, autocorrection is an absolute pain.

Yes, but a non-functioning Mac Pro keyboard that adds or omits characters. at will is. hell.

At. least they are now willing to repair their crappy hardware, but I still have to find the right moment to do without this thing for a few. days.

And here the alternative code snippet:

<?php
$firstImage = $page->images()->filterby('isLandscape', true)->shuffle()->first();
$allImages = $page->images()->not($firstImage)->shuffle();
if($firstImage) {
  $allImages = $allImages->prepend($firstImage->filename(), $firstImage);
}
?>
<?php foreach($allImages as $image): ?>
  <img src="<?= $image->url() ?>" alt="">
<?php endforeach ?>

Don’t you have an external keyboard you can hook up your laptop until you can get it fixed?

@texnixe I would give this a shot before resigning it to the apple store. https://support.apple.com/en-gb/ht205662 Can get compressed air pretty cheap at places like Amazon.

This works so well!! Thank you so much.