Getting structure field values from multiple pages without duplicates

I have many product-pages, each page has a field labled »size« (inside a structure field). I’d like to create an array containing all available sizes, without containing duplicates.

My approach was to initialise an empty array, then iterate over a collection of all product-pages and push a page’s size-field value into the array, after checking if the array does not already contain the value (i.e. the value is only pushed if its not contained in the array, at least that’s the idea). My code:

$products        = page("products")->children()->listed(); 
$sizes_available = [];

foreach($products as $product) {
  $size = $product->variants()->toStructure()->first()->size();

  if(in_array($size, $sizes_available) == false) {
    array_push($sizes_available, $size);
  }
}

However, this doesn’t seem to work. When outputting $sizes_available, it contains the size-field value of every product page.

What am I doing wrong? Thanks in advance

Does your structure field have only one item with a size? If so, why is it inside a structure field?

To get the value instead of the field object:

$size = $product->variants()->toStructure()->first()->size()->value();

Your code is error-prone though in the case $product->variants()->toStructure() is empty. Better:

 $size = ( $item = $product->variants()->toStructure()->first() ) ? $item->size()->value() : null;