# Slider PHP loop

I am working on a image slider for a website, the user can add up to 0 - 3 images to the slider. What kind of loop should I use to make this code more efficient and DRY? "data-slide-number" starts from 0 and changes based on the image. The images are not "required" so there won't always be 3 images.

<?php
// image urls
$pr_img_1 = first image url;$pr_img_2       = second image url;
$pr_img_3 = third image url; ?> <div class="carousel-inner"> <?php if($pr_img_1); { ?>
<div class="active item" data-slide-number="0">
<img src="<?= esc_html( $pr_img_1 ); ?>"> </div> <?php } ?> <?php if($pr_img_2); { ?>
<div class="active item" data-slide-number="1">
<img src="<?= esc_html( $pr_img_2 ); ?>"> </div> <?php } ?> <?php if($pr_img_3); { ?>
<div class="active item" data-slide-number="2">
<img src="<?= esc_html( $pr_img_3 ); ?>"> </div> <?php } ?> </div><!-- Carousel nav -->  ## 1 Answer You can follow the below code. <?php$pr_imgs = array("first image url","second image url","third image url");
$i = 0; foreach($pr_imgs as $pimg) { ?> <div class="active item" data-slide-number="<?php echo$i; ?>">
<img src="<?= esc_html( $pimg ); ?>"> </div> <?php$i++;
}
?>


Using foreach you don't have to take care of the number of image path.

• yes, perfect answer – Rohit Goyani Jul 14 '16 at 17:43