I’m trying to repeat a foreach loop from a files field until the count meets at least 10 images. The foreach needs to escape so i can use thumbs and srcset.
For example, if the user has uploaded 5 images it’ll run twice, if 2 images then 5 times, if 10 images then once, if 11 then it’ll load the first 10.
I think i’m completely barking down the wrong tree but so far i’ve been pulling range to repeat the list then was thinking to cull it down to 10 images - is this the right way to go around this?
This however cuts off anything over 10 but it doesn’t repeat the loop if theres less than 10 objects in the field. I need it to repeat it until theres 10 iterations of the objects.
So if the user only uploads say 2 images into the field, it will repeat it 5 times to make sure theres 10 images being rendered.
Sorry Paul, I indeed missed that aspect of your question! I like the Array approach above, yet here’s how I would probably have approached this without Sonja’s input (also untested, extending on my earlier suggestion of utilizing the break statement):
The while loop restarts as long as $i has not reached 10 yet, then the foreach loop gets executed on every iteration of the while loop. In case we reach 10 within the foreach loop, it is interrupted by break and then the while loop will be exited because its condition is no longer true.
…that said, I’d personally drop my own approach and go with @texnixe’s suggestion.
PS: I took the freedom to add the missing alt attribute to your <img> tag for accessibility
I haven’t dealt with arrays much so stumbling my way through it and don’t quite get the result i’m after. Probably doing this completely wrong but the last result I got loaded the src with 10 iterations of the same URL wrapped in <pre> tags.
<?php
// Get a max of 10 files
// Convert collection to array to reset item keys
$images = $project->imagery()->toFiles()->limit(10)->values();
// Add items until there are at least 10 of them
while (count($images) < 10) {
array_push($images, ...$images);
}
// Ensure there are 10 items in the end
$images = array_slice($images, 0, 10);
?>
<?php foreach ($images as $image) : ?>
<img class="lazy" src="<?= $image->thumb('standard')->url() ?>" srcset="<?= $image->thumb('standard')->url() ?>" data-src="<?= $image->url() ?>" data-srcset="<?= $image->srcset([720, 1280, 1920]) ?>" alt="" />
<?php endforeach ?>
// ...
// Add items until there are at least 10 of them
while (count($images) < 10) {
- array_push($images, ...$images);
+ array_push($images, ...array_slice($images, 0, 10 - count($images)));
}
-
- // Ensure there are 10 items in the end
- $images = array_slice($images, 0, 10);
No error log is being generated and its still not working.
Completely crashes the page with a 500 error so it doesn’t even hit the debug screen which is turned on in config.