'limit number of categories output with get_the_terms

I'm trying to limit the number of taxonomies output in my comma separated list of categories. Here's the code I'm using to display all of them in a list.

<?php

    $post_id = get_the_ID();

        $taxonomy= 'location';

    $terms = get_the_terms($post_id, $taxonomy);

    if ($terms) {
      $term_arr = array();

        foreach ($terms as $term) {
          $name = $term->name;
          $term_arr[] = $name;
        }
      
      $my_terms = implode (", ", $term_arr);
      
    }
?>

<div class=""><?php echo $my_terms; ?>.</div>

Thanks for your time.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source