Shuffle until first image satisfies condition


#1

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!


#2

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 ?>

#3

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


#4

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


#5

I hear you, autocorrection is an absolute pain.


#6

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.


#7

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 ?>

#8

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


#9

@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.


#10

This works so well!! Thank you so much.