Sorry, I didn't mean to insult, especially if you're a PHP beginner and wrote the code yourself. I was in a hurry when I replied to your post. I thought that you were using someone else's package, in which case I would have recommended something more robust. Basically I was trying to prevent you from reinventing the wheel. There are literally hundreds of image gallery scripts out there, at least one of which almost certainly meets your requirement.
Concerning your code, the trouble is that you mix data, logic, and presentation so heavily, that in the end your code will be very difficult to maintain. HTML should be kept separate from the PHP as much as possible, as should the data describing your images.
I know for newbies this is a troublesome concept, because most beginning PHP books and tutorials start out saying, "look how easy it is to mix PHP and HTML!"
Once again, I didn't mean to insult you and I hope I haven't discouraged you from using PHP or our forum.