Undefined variable in block

Hi there,

it’s probably a lame question but I can’t find the mistake in my php code, so maybe someone sees it.

I defined an own block type and this is the code:

<section class="schedule">
  $events = $page->events()->toStructure()->filter(function ($child) {
    return $child->date()->toDate() > time();
  $months = array();
  foreach ($events as $event) :
    $months[] = strftime('%b %Y', strtotime($event->date()));
  $filteredmonths = array_unique($months);
  foreach ( $filteredmonths as $month) : ?>
    <div class="headline">
      <h2><?= $month ?></h2>
    <div class="grid">
      $monthevents = $events->filter(function ($child) {
        return strftime('%b %Y', strtotime($child->date())) == $month;
     foreach ($monthevents as $event) : ?>
       <div class="event">
         <span><?= $event->date() ?></span>
         <h3><?= $event->heading() ?></h3>
         <a href="<?= $event->url() ?>">More info <?php snippet('angleright') ?></a>
     <?php endforeach ?>
  <?php endforeach ?>

And I get the error:
Block error: "Undefined variable: monthnow" in block type: "schedule"

I already found out that the problematic $month variable is the one used inside the filter function, but I don’t know why I cannot use it there but use it above.

Thank you in advance!

You have to use the use keyword to pass the variable to the callable, because the outer variable is not known inside.

  $monthevents = $events->filter(function ($child) use($month) {
        return strftime('%b %Y', strtotime($child->date())) == $month;

Now it works. Thank you very much @texnixe as always!