0
\$\begingroup\$

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
asked Jul 14, 2016 at 8:38
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ yes, perfect answer \$\endgroup\$ Commented Jul 14, 2016 at 17:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.