Search code examples
phploopsdirectoryglob

Using glob() to display images from a directory while echo'ing a unique first image


I am quite new to PHP and I did not want to ask anything here until I absolutely could not find a way to do this.

I have a situation where I would like to use PHP to read and display images from a directory but I would like the first image read to be echo'd uniquely

My current code as follows:

$imageDir = "img/landMarks/carousel/";
$images = glob($imageDir.'*.jpg');
foreach ($images as $image){
echo '<div class="item">'."\r\n\t\t";
echo '<img src="'.$image.'" alt=""></div>'."\r\n\t";}

Just a simple directory pull and echo with formatting.

This will be for a BootStrap carousel and unfortunately the first image in line has to have <div class="item active"> or the whole thing fails.

So to reiterate, the first image pulled needs to be <div class="item active"> while the rest need to be <div class="item">

I think I went through an entire pack of cigarettes wracking my brain around this.


Solution

  • use a flag for that. hope to help.(-:

    $imageDir = "img/landMarks/carousel/";
    $images = glob($imageDir.'*.jpg');
    $flag=1;
    foreach ($images as $image){
    echo '<div class="item' .($flag?' active':''). '">'.PHP_EOL."\t\t";
    echo '<img src="'.$image.'" alt=""></div>'.PHP_EOL."\t";
    $flag=0;
    }