Reputation: 45
I'm using a php gallery script and I need to add numbers (auto increment) in the "alt" field (images). I already tried several options from stackoverflow and unfortunately I didn't succeed.
For example: For each image added, alt field should be like this:
alt="adidas 1">
alt="adidas 2">
alt="adidas 3">
alt="adidas and more">
My HTML output should be like:
<div class="gallery">
<img src="./products/adidas-cushon.webp"/ alt="adidas 1">
<img src="./products/adidas-majestic.webp"/ alt="adidas 2">
<img src="./products/adidas-wear.webp"/ alt="adidas 3">
</div>
My script
<!-- (A) CSS & JS -->
<link href="gallery/gallery.css" rel="stylesheet">
<script src="gallery/gallery.js"></script>
<div class="gallery"><?php
// (B) GET LIST OF IMAGE FILES FROM GALLERY FOLDER
$dir = __DIR__ . DIRECTORY_SEPARATOR . "./products/adidas/" . DIRECTORY_SEPARATOR;
$images = glob("$dir*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
//rsort($images); // high to low
//sort($images); // low to high
natsort ($images); //
// (C) OUTPUT IMAGES
foreach ($images as $i) {
printf('<img src="./products/adidas/%s" alt="adidas">', basename($i));
}
?></div>
Upvotes: 0
Views: 49
Reputation: 2137
Use the array index key in your foreach and add 1.
foreach ($images as $i => $path) {
printf('<img src="./products/adidas/%s" alt="adidas %s">', basename($path),$i+1);
}
Upvotes: 1