MyRevenge
MyRevenge

Reputation: 117

php limit foreach to only show item once

I have tried for a couple of days to figure out how to do this, but I can't seem to figure it out. I am using woocommerce to show one variation of each colour.

But I cannot find out how to limit them.

As for right now I have made a script which removes the duplicates but I don't think it's that good of a solution.

The code has been taken from inside the loop on an archive page.

The code I am working with is as following:

<?php 
$terms = get_terms("pa_color");
foreach ( $terms as $term ): ?>
    <?php $variations = $product->get_available_variations(); ?>
    <?php foreach ($variations as $attributes => $value): ?>
        <?php $color = $value[attributes][attribute_pa_color]; ?>
        <?php if ($color === $term->slug): ?>
            <?php echo $color; ?>
        <?php endif ?>
    <?php endforeach ?>
<?php endforeach; ?>

So as you can see i first get the colours for the product with get_terms and then use a foreach loop, I don't know if it is the right way to do it, so i hope you guys can help.

Upvotes: 1

Views: 904

Answers (1)

TestUser1
TestUser1

Reputation: 383

You could use the break statement

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

example the first two items. Change '2' to whatever number you want.

Upvotes: 1

Related Questions