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 -->
\$\endgroup\$
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.

|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ yes, perfect answer \$\endgroup\$ – Rohit Goyani Jul 14 '16 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.