Last item in structure field?

How to filter the last item in foreach loop of the structure field?

i don’t know if there’s a Kirby native method, but you could check the top voted reply here and build your logic from there:

1 Like

If you want to get the last item in a structure, you would not loop through it, but just fetch it:

$lastItem = $page->structureField()->toStructure()->last();

Not sure if that’s what you want though.

To check if the current item in the loop is the last item, you can do it like this:

$items = $page->structureField()->toStructure()
foreach ($items as $item ) {
  if ( $item === $items->last() ) {
    echo 'Yay, this is the last item';
  }
}

Or, depending on your context, shorten this using the ternary operator:

<?php echo $item === $items->last() ? 'last-item' : ''; ?>

You can use this for all types of collections: collection, users, pages, files, structure.

1 Like

of course… :sweat_smile:

Yes, thank you both very much :slight_smile:

I should get some sleep, kept trying this to prevent adding a custom class to the last item

<?php foreach($site->social()->toStructure() as $social): ?>

<a href="<?= $social->url() ?>"<?php e(!$social->last(), ' class="custom-class"') ?></a>

<?php endforeach ?> 

Which doesn’t work. :upside_down_face:

last() is not a function on the StructureItem to check if it’s the last item, it’s a function on Structure to fetch the last of all items. Like in texnixe’s example above, you would have to compare the current item with the last item of the structure to know if “current is last”.

<?php e($social !== $site->social()->toStructure()->last(), ' class="custom-class"') ?>
1 Like

Just to conclude what works

This works

<?php 
$socials = $site->social()->toStructure();
foreach($socials as $social): ?>
<a href="<?= $social->url() ?>"<?php e($social !== $socials->last(), ' class="custom-class"') ?>></a>
<?php endforeach ?>

Also, this works

<?php 
$socials = $site->social()->toStructure();
foreach($socials as $social): ?>
<a href="<?= $social->url() ?>"<?php e(!next($socials), ' class="custom-class"') ?>></a>
<?php endforeach ?>

But this doesn’t

<?php foreach($site->social()->toStructure() as $social): ?>
<a href="<?= $social->url() ?>"<?php e($social !== $site->social()->toStructure()->last(), ' class="custom-class"') ?>></a>
<?php endforeach ?>

If someone gets stuck in a similar problem.