Best way to include html inside foreach loop?

I am trying to build a slider using Wordpress Plugin Advanced Custom Fields.

With the plugin, I have made a repeater which contains an image and a caption field (among others).

The code below works, but it seems asinine to have to use so many echo commands (since there are so many html tags.

I’m a PHP novice. Is there a better way to do this?

<div class="slider">
<?php 
$rows = get_field('gallery_repeater');
echo "I have a gallery repeater";
if( $rows ) {
    foreach( $rows as $row ) {
        $repeater_image = $row['gallery_repeater_image'];
            $repeater_image_url = $repeater_image['url'];
            $default_caption = $row['gallery_repeater_caption'];
        if ($default_caption) {
            $image_caption = $default_caption;
        }
        else {
            $image_caption = $repeater_image['caption'];
        }
              
        
        echo '<div class="slide"> <img src="';
        echo ($repeater_image_url);
        echo '">';
        echo '<p>';
        echo ($image_caption);
        echo '</p> </div>';
        
        
        
        

      
        
       
    }
}

?>
</div><!-- end slider -->

Yeah you can use a single echo and embed your variables in it.

echo "<div class=\"slide\"><img src=\"$repeater_image_url\"><p>$image_caption</p></div>";

I would recommend reading the PHP page on echo. It has a ton of very useful things that even most experienced PHP developers don’t know about echo and what it can do. Definitely worth the time to read through it.

https://www.php.net/manual/en/function.echo.php

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.