So far our PHP gallery examples have required us to write new HTML code in order to present an image in the gallery, or at least the thumbnail thereof. This means that every time that we upload a new image to the site, we would have to write more HTML to add it to our page.
But our random image lesson showed that we can read images from a directory… so it follows that we should be able to automate the entire process of presenting a gallery of images with PHP.
Let’s take the core of the random image code:
- <?php $imagedir = dir('assets/images');
- $count = 1;
- $pattern="/\.(gif|jpg|jpeg|png)$/";
- while(($file = $imagedir->read())) {
- if (preg_match($pattern, $file)) {
- $imagearray[$count] = $file;
- $count++; }
- } ?>
This creates our array as before. But this time, we’re not getting a random image from $imagearray, but the first image. Doing that alone would be easy:
- <img src="assets/images/<?php echo $imagearray[1]; ?>" alt="">
We want to make what selects the image a variable, so let’s create one called $pic and set it to a default value of 1 if no value for it exists:
- <?php if (!$pic) { $pic = 1; } ?>
- <img src="assets/images/<?php echo $imagearray[$pic]; ?>" alt="">
Now we want to allow the user to change the value of $pic. The easiest way to do that is via clicking on a link which passes a GET variable back to the page. First, we’ll add a line of code to the section above:
- <?php $pic = $_GET['pic'];
- if (!$pic) { $pic = 1; } ?>
- <img src="assets/images/<?php echo $imagearray[$pic]; ?>" alt="">
Then create our link, which will increment whatever value $pic has by 1:
- <a href="?pic=<?php echo ($pic + 1); ?>">Next</a>
This will advance our images through the array with each click on the Next link. (As always, one of the easiest ways to understand this is to look at the source code delivered from the browser). There’s just one problem: we can keep clicking the Next button past the actual number of images we have.
To solve this, we’ll make the appearance of the Next button conditional:
- <?php if ($pic < $count - 1) { ?>
- <a href="?pic=<?php echo ($pic + 1); ?>">Next</a>
- <?php } ?>

Haha, that is actually incredibly clever.
![Prometheus: Collector's Edition (Bilingual) [Blu-ray 3D + Blu-ray + DVD + Digital Copy] Prometheus: Collector's Edition (Bilingual) [Blu-ray 3D + Blu-ray + DVD + Digital Copy]](http://ecx.images-amazon.com/images/I/5192I1rtYnL._SL160_.jpg)

