I have a folder containing images that I want to put inside a Bootstrap carousel. Instead of hardcode everything in my HTML, I thought to use PHP to scan the image files and create my carousel list dynamically.
After various attempts, my best achievement was having a carousel listing the names of my images (rather than the image themselves).
My code is below. I have two question about it:
- (obviously) Why is it not working?
Is there a better way to separate such a long PHP function from the HTML code (like a call with
include
but that would work with functions)?<div class="container-fluid"> <?php $img_folder = './img/img_animazione/'; function carousel_loop($folder) { echo '<div id="myCarousel" class="carousel slide" data-ride="carousel">'; echo '<ol class="carousel-indicators">'; $i = -1; $images = scandir($folder); foreach($images as $image) { $i++; //$i is the index of the current loop. if ($i == 0) { echo '<li data-target="#myCarousel" data-slide-to="' . $i . '" class="active"></li>'; } else { echo '<li data-target="#myCarousel" data-slide-to="' . $i . '"</li>'; } } echo '</ol>'; echo '<div class="carousel-inner">'; foreach($images as $image) { if ($image === reset($images)) { echo '<div class="item active">'; echo '<img src="' . $image . '" alt="'. $image . '">'; echo '</div>'; } else { echo '<div class="item">'; echo '<img src="' . $image . '" alt="'. $image . '">'; echo '</div>'; } } echo '</div>'; echo '<a class="left carousel-control" href="#myCarousel" data-slide="prev">'; echo '<span class="glyphicon glyphicon-chevron-left"></span>'; echo '<span class="sr-only">Previous</span>'; echo '</a>'; echo '<a class="right carousel-control" href="#myCarousel" data-slide="next">'; echo '<span class="glyphicon glyphicon-chevron-right"></span>'; echo '<span class="sr-only">Next</span>'; echo '</a>'; echo '</div>'; } carousel_loop($img_folder); ?> </div>