How to show variations only which are in stock on shop page in woocommerce?

I got an answer from stackoverflow, this works but the all the sizes are being shown in a single button, I want to show all sizes in separate buttons, like the above screenshot has.
I know its possible by adding a loop before echoing my button, my loop is not working

    global $product;

    if ( $product->is_type('variable') ) {
        $taxonomy    = 'pa_sizes'; // The product attribute taxonomy
        $sizes_array = []; // Initializing

        // Loop through available variation Ids for the variable product
        foreach( $product->get_children() as $child_id ) {
            $variation = wc_get_product( $child_id ); // Get the WC_Product_Variation object

            if( $variation->is_purchasable() && $variation->is_in_stock() ) {
                $term_name = $variation->get_attribute( $taxonomy );
                $sizes_array[$term_name] = $term_name;
            }
        }

        echo '<button class="btn btn-circle btn-lg rounded-circle">' . implode( ', ', $sizes_array ) . '</button>';
    }

So, can anybody add a loop just before echoing the button so that I can display all available sizes in different buttons.