Remove duplicates from echo output in PHP

Right now the below function outputs all variations images of a product. E.g. 3x blue (size S, M, L), 3x red (size S, M, L)

I would like the below function to only output unique color images. E.g. 1x blue, 1x red

Tried to use array_unique in the echo string but could not get it working.

Thank you for helping.

function loop_display_variation_attribute_and_thumbnail() {
    global $product;
    if( $product->is_type('variable') ){
        foreach ( $product->get_visible_children() as $variation_id ){
            // Get an instance of the Product_Variation object
            $variation = wc_get_product( $variation_id );

            // Get "color" product attribute term name value
            $color = $variation->get_attribute('pa_color');

            if( ! empty($color) ){
                // Display "color" product attribute term name value
                echo $color;

                // Display the product thumbnail with a defined size (here 30 x 30 pixels)
                echo $variation->get_image( array(30, 30) );
            }
        }
    }
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

This is more of a PHP programming question than specific to WordPress, but you could do something like this.

This keeps a track of which colors have been shown in $shownColors array and doesn’t show the same one twice.

function loop_display_variation_attribute_and_thumbnail() {
    global $product;
    if( $product->is_type('variable') ){

        $shownColors = Array();

        foreach ( $product->get_visible_children() as $variation_id ){
            // Get an instance of the Product_Variation object
            $variation = wc_get_product( $variation_id );

            // Get "color" product attribute term name value
            $color = $variation->get_attribute('pa_color');

            if( ! empty($color) && !in_array($color, $shownColors) ){
            // Display "color" product attribute term name value
                echo $color;

                // Display the product thumbnail with a defined size (here 30 x 30 pixels)
                echo $variation->get_image( array(30, 30) );

                $shownColors[] = $color;  // add this to colors we've shown
            }
        }
    }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply