I have a slider for scrolling through images, and I add all the images to the slider through php
The situation is that the slider needs at least 4 images to work, and I wrote the corresponding code that copies and pastes the images, if we add only one or two
Here is the working code
<?php if (count($images) < 4) { ?>
<?php
$images = array_merge($images, $images);
$images = array_merge($images, $images);
$images = array_slice($images, 0, 4);
foreach ($images as $image) {
if ($image->image_id) { ?>
<div class="slider-image">
<img src="<?= $image->url ?>" alt="<?= $image->name ?>">
</div>
<?php } ?>
<?php } ?>
<?php } ?>
And there is this line
if ($image->image_id)
That is, I may have a situation that such an image is not in the database, and so that there are no errors, I added the appropriate check
So, if I have an image that is not in the database, then this copy code does not work, since it copies an empty image, which is then not displayed
$images = array_merge($images, $images);
$images = array_merge($images, $images);
$images = array_slice($images, 0, 4);
How can I take into account the factor that the picture is not in the database and correct the code for copying? Or do I need to use another implementation here?
I presume your $images
is not empty and is a regular list (has sequental zero-based indices). Just populate the images array in the loop as:
$images = [0,1];
$i = 0;
while( count( $images ) < 4 )
$images[] = $images[ $i++ ];
print_r($images); # [0,1,0,1]
/*
For given initial arrays we will get following results:
[0] -> [0,0,0,0]
[0,1] -> [0,1,0,1]
[0,1,2] -> [0,1,2,0]
[0,1,2,3] -> [0,1,2,3]
*/
If you have some dummy images objects - filter them out first:
$images = array_filter($images, fn($image) => !empty($image->image_id) );