Having issues with a foreach inside of a shortcode with ACF gallery

Normally I would just put this type of content in a template, but the way I’m pulling in the content is a bit different. I made a shortcode which I’ve been having issues with. It’s using Foundation 5’s orbit slider and an ACF Gallery. It’s getting hung up on the foreach part.

// Add Shortcode
function custom_carousel($atts, $content = null) {
    extract(
      shortcode_atts(
        array(), $atts));
    $out1 = '<ul class="orbit" data-orbit data-options="timer_speed:1500;">';
    $carouselimages = get_field('gallery');
    foreach ($carouselimages as $carouselimage) {
        $output = ' <li class="text-center"> <img src="' . $carouselimage['url'] . '" title="' . $carouselimage['title'] . '" alt="' . $carouselimage['alt'] . '" /></li>';
    }
    $out3 = '</ul>';
    return $out1 . $output . $out3;
}

add_shortcode('custom-carousel', 'custom_carousel');

I’m using this code for the mobile version of the site in the template which works perfectly:

<?php
$carouselimages = get_field('gallery');
if ($carouselimages) {
    ?>
            <ul class="orbit" data-orbit data-options="timer_speed:1500;">
                <?php foreach ($carouselimages as $carouselimage) { ?>
                    <li class="text-center">
                        <img src="<?php echo $carouselimage['url']; ?>" title="<?php echo $carouselimage['title']; ?>" alt="<?php echo $carouselimage['alt']; ?>" />
                        <?php echo $carouselimage['description']; ?>
                    </li>
                <?php }; ?>
            </ul>
<?php } ?>

Solutions Collecting From Web of "Having issues with a foreach inside of a shortcode with ACF gallery"

At first – do not use extract. It’s very bad code style and is also depracated in core.

Every time your foreach loop run, you override content of $output because you assign to this variable new content. What you want is to concatenate new list item with existing ones. This can be done using concatening assignment operator:

$output .= '<li class="text-center"> <img src="' . $carouselimage['url'] . '" title="' . $carouselimage['title'] . '" alt="' . $carouselimage['alt'] . '" /></li>';

$output variable should be defined before your foreach statement. Just assign to it an empty string.