\$\begingroup\$
\$\endgroup\$
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 -->
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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.
answered Jul 14, 2016 at 12:20
-
\$\begingroup\$ yes, perfect answer \$\endgroup\$Rohit Goyani– Rohit Goyani2016年07月14日 17:43:05 +00:00Commented Jul 14, 2016 at 17:43
lang-php