Giving a unique identifier to elements in a for loop

How can I give unique identifier to the <a> element in my second for loop? Perhaps an ascending attribute like num="1". The for loop is the output of using @thguenther’s Kirby-Images plugin.

<?php foreach($pieces as $piece): ?>
   <div id="<?= $piece->uid() ?>">
       <?php foreach($piece->thumbnails()->yaml() as $image): ?>
            <?php if($image = $piece->image($image)): ?>
                 <a href="<?= $piece->url(); ?>" class="load" data-slug="<?php echo str::slug($piece->title())?>">
                     <img src="<?php echo imgix($image, array('w' => 300)) ?>" />
                 </a>
             <?php endif ?>
        <?php endforeach; ?>
     </div>
<?php endforeach ?>

You can set a $num variable before the loop, and increment it right after the foreach declaration :

<?php $num = 0; foreach($piece->thumbnails()->yaml() as $image): $num++; ?>

or use toStructure instead of yaml, and get the index of the image within its structure :

<?php 
$images =  $piece->thumbnails()->toStructure();
foreach($images as $image): $num = $images->indexOf($image); ?>

Then you can access the $num variable inside the loop and use it for an id or data-attribute.

1 Like

thanks for taking the time to reply, they both work great!