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;

The structure field actually only contains one entry, with a size. My question is based on the Kirby Shopify plugin which comes with a blueprint for products. The blueprint puts all variants of a Shopify product (received via web hook) into a structure field. In my special case, there is only one size/variant of each product (hence the structure field with a single entry).

In the end, I was able to get what I needed by using the array_unique method:

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

foreach($products as $product) {
  $size = $product->shopifyVariants()->toStructure()->first()->title()->value();
  array_push($options_sizes_temp, intval($size));

$options_sizes = array_unique($options_sizes_temp);