I’m trying to create an array with a foreach loop, but the array only stores the last item [closed]

Try this code. is it necessary to unset that arrays in foreach? unset inside loop will remove the previous array values.

<?php
    //Get posts by the arguments saved in the $args array
    $vendor_postlist = get_posts( $args );
    $categories = array();
    // Loop the list of posts obt.....
    foreach ( $vendor_postlist as $post ){  

    $terms = get_the_terms( $post->ID, 'product_cat' );


    foreach ( $terms as $term ) {
    $categories[] = $term->name;
    echo $term->name;
    }

    }

    print_r($categories);
    ?>

tech