Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need my loop to stop when a file doesn't exist

Tags:

loops

php

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'">';
    }
}
like image 769
izolate Avatar asked Nov 19 '25 01:11

izolate


1 Answers

what about scandir ?

$dir    = '/images';
$imgs = scandir($dir);

foreach($imgs as $img)
{
  if($img != '.' && $img != '..')
  {
    echo '<img src="http://localhost/images/'.$img.'">';
  }
}
like image 195
Zul Avatar answered Nov 21 '25 14:11

Zul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!