Problems with hasNext()


I’m not sure, what I’m missing here, maybe someone can help me with that.
I’m trying to add a red border to the last image of the loop, and If it’s not the last image, add a green border.

<?php if($gallery = $page->images()->sortBy('sort')): ?>

<ul class="gallery">

<?php foreach($gallery as $image): ?>
<li class="gallery__item" style="<?= e(!$image->hasNext(), 'border: 10px dashed red;', 'border: 2px dashed limegreen;') ?>">
  <figure itemprop="associatedMedia" itemscope itemtype="" >
    <img src="<?= $image->url(); ?>" alt="<?= $image->title()->kti() ?>" itemprop="thumbnail">
    <figcaption><?= $image->alt()->html() ?></figcaption>
<?php endforeach ?>

<?php endif ?>

Right now, this results is having the first image with a green border and all others with red ones!?

Rather then using logic logic and inline styles, you can actually do this just with CSS. Give all the images the green border, and use :last-of-type on the li elements to change the image border on the last one.

.gallery img {
  border: 10px solid limegreen;

.gallery li:last-of-type img {
  border: 10px solid red;

I agree with @jimbobrjames.

But to come back your problem here, you probably have to invert your condition (== remove the ! in your e-function).

Thank You @jimbobrjames, You’re completely right.
I broke this code down to a simpler example than my use case actually is.

Thanks @bvdputte, I already tried to invert the condition.
The actual error was a missing “sort” field for one of the images.
Now both hasNext() and isLast() work as expected.


PS: I would never add a 10px dashed red border to an image :smiley: