Don’t use $var++
and $var--
when displaying a variable. The way it works is a bit tricky: it returns the old value, not the new one. If you want to return the new value, you have to use the ++
or --
operator in front of the variable name, like this: ++$var
, --$var
.
Frankly that’s a bit messy and you’re going to confuse yourself or confuse the next person working on this code. Avoid it, if you can.
If I take your code and just keep the parts where you use the $i variable:
<?php $i = 1; foreach([0,0] as $test): ?>
Current: <?php echo $i ?><br>
Previous: <?php echo $i-- ?><br>
Next: <?php echo $i++ ?><br><br>
<?php $i++; endforeach ?>
… for two iterations the result looks like this:
Current: 1
Previous: 1
Next: 0
Current: 2
Previous: 2
Next: 1
What you want to do is only increment the value of $i
at the end of the iteration. So only use $i++
at the end, and when trying to get the other values use $i - 1
and $i + 1
. That would be a start, though it won’t fix your loop needs.
Side note: with your current HTML code you are embedding EVERY BIG IMAGE IN THE PAGE. That’s a performance nightmare if your big images are heavy (like hundreds of kilobytes or, worse, a few megabytes — which you should never ever have on a website obviously). Browsers are still going to download these images even if your CSS or JS code hides them, because at the time when the browser requests the page’s resources (CSS, JS, images etc.) it doesn’t know if they are going to be hidden or not.
There are some good image gallery scripts out there that recommend more reasonable markup, such as:
<ul class="gallery">
<li><a href="big-image-1.jpg"><img src="thumb-1.jpg" alt="Alt text for that image"></a></li>
<li><a href="big-image-2.jpg"><img src="thumb-2.jpg" alt="Alt text for that image"></a></li>
<li><a href="big-image-3.jpg"><img src="thumb-3.jpg" alt="Alt text for that image"></a></li>
</ul>
Without JS, it’s a list of small images that link to the bigger images. Ideally, each image (and thus each link) should have relevant alternative text. Then, with JS, when clicking the small image you can get a full-screen gallery.
Some good scripts: Photoswipe, Magnific Popup, and a few more.