Call structure field item before foreach loop


I have a structure field with dates.
Plus some if statements. Expired dates are not displayed.
I would like to hide the complete container if no dates has been entered or all dates are in the past.

  <?php $items = $page->freie_zeiten()->toStructure();
  foreach ($items as $item): ?>
    <?php $today = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
    if($item->bis()->toDate() > $today): ?>
        <?php $today_von = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
        if($item->von()->toDate() >  $today_von): ?>
          <?= $item->von()->toDate('d.m.Y') ?> -
        <?php else: ?>
        <?php endif ?> 
        <?= $item->bis()->toDate('d.m.Y') ?>
    <?php endif ?>
  <?php endforeach ?>

I think I would have to call the single item before the foreach loop.
But I failed.

That was an idea:

$items  = $page->freie_zeiten()->toStructure();
$item = ????
if($item->count() < 1):
    foreach  loop
<?php endif ?>

Thank you for your help.

What I’d do is filter the structure items by date, no need for if statements on the item itself. Then check if the resulting structure collection isNotEmpty().

you can filter the structure before displaying it

$items = $page->freie_zeiten()->toStructure();
$items = $items->filter(...); // add your date check
if ($items->count() > 0): // show them

@texnixe and @bnomei
Great thank you. Works as it should! :+1: