I have a set of related images in my /images/ directory named sequentially as image1.jpg, image2.jpg, image3.jpg etc...
I'm trying to output the images in my markup with PHP using a loop. But since the number of images varies, I need it to stop when it gets to the last image file in the directory.
Say I have 5 images, I want it to only output:
<img src="images/image1.jpg">
<img src="images/image2.jpg">
<img src="images/image3.jpg">
<img src="images/image4.jpg">
<img src="images/image5.jpg">
And if I add image6.jpg to the directory, it should automatically add to the markup. How do you do this?
My current method
for ( $i=1; $i<100; $i++ ) {
if ( file_exists('http://localhost/images/image' . $i . '.jpg') ) {
echo '<img src="http://localhost/images/image' . $i . '.jpg'">';
}
}
what about scandir ?
$dir = '/images';
$imgs = scandir($dir);
foreach($imgs as $img)
{
if($img != '.' && $img != '..')
{
echo '<img src="http://localhost/images/'.$img.'">';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With