tags:

views:

23

answers:

2

How can i list images in a folder...(which could be any number) and echo them in a list making the sure the first li has a class of "first" and the the last list item has a class of "last" like so...

<li class="first"><img src="flowing-rock.jpg" /></li>
<li><img src="stones.jpg" alt="Stones" /></li>
<li><img src="grass-blades.jpg" /></li>
<li><img src="ladybug.jpg" alt="Ladybug" /></li>
<li class="last"><img src="pier.jpg" alt="Pier" /></li>

Any help would be appreciated...

+1  A: 

The following will select the first and last (if they exist), printing them before and after the rest, respectively. These are sorted alphabetically by scandir().

$contents = scandir(DIRECTORY);
array_pop($contents); // Remove "."
array_pop($contents); // Remove ".."
$last = array_pop($contents); // Grab last element
$first = array_shift($contents); // Grab first element

// print elements
if (!is_null($first)) echo "<li class='first'><img src='$first' /></li>\n";
foreach ($contents as $key => $val)
    echo "<li><img src='$val' /></li>\n";
if (!is_null($last)) echo "<li class='last'><img src='$last' /></li>\n";
Nerdling
cheers for all your help, this works great!
jeffery
A: 

You can use glob to scan for image files, then check the index of the current array element:

$imgs= glob('/path/to/images/*.jpg');

for ($i=0; $i<count($imgs); $i++) {
 if ($i == 0) $class= ' class="first"';
 else if ($i == count($imgs)-1) $class= ' class="last"';
 else $class= '';
 printf("<li%s><img src=\"%s\" /></li>\n", $class, htmlentities(basename($imgs[$i])));
}

Take out the basename call if you want to keep the directory name.

pygorex1
Thanks for your response i went with the first one...thanks again!
jeffery