简体   繁体   中英

list images in a directory with php and add a specific class

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...

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM