SeRosiS
SeRosiS

Reputation: 63

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.

Upvotes: 2

Views: 1491

Answers (2)

Sina R.
Sina R.

Reputation: 1788

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;
}

Upvotes: 2

Kevin
Kevin

Reputation: 513

How about using a for loop instead of a foreach loop. When index == 0 you can add "active" to your div's class.

Note I didn't run this code- but it should give you the right idea.

$imageDir = "img/landMarks/carousel/";
$images = glob($imageDir.'*.jpg');
for($i = 0; $i < count($images); $i++){
       //If the index is 0, it's the first image.
       $class = ($i == 0) ? 'item active' : 'item';

       //Dynamically change your div's class
       echo "<div class='$class'>\r\n\t\t";
       echo '<img src="'.$images[$i].'" alt=""></div>'."\r\n\t";
}

Upvotes: 1

Related Questions