<?php [$instructions, $mine, $others] = explode("\n\n", file_get_contents('input.txt')); // parse instructions function parseInstructions($instructions) { // class: 1-3 or 5-7 preg_match_all('/^[a-z]+: (\d+)-(\d+) or (\d+)-(\d+)$/mi', $instructions, $matches); if (count($matches) !== 5) { echo sprintf('Regex failed : %s', var_export($matches, true)); exit; } $compares = []; array_shift($matches); for ($i = 0, $l = count($matches[0]); $i < $l; $i++) { $compares[] = static function ($number) use ($matches, $i) { $comparison = ($number >= (int)$matches[0][$i] and $number <= (int)$matches[1][$i]) || ($number >= (int)$matches[2][$i] and $number <= (int)$matches[3][$i]); if ($comparison === true) { return true; } return $number; }; } return $compares; } $compares = parseInstructions($instructions); // check others $others = explode("\n", $others); array_shift($others); $others = array_map(static function($other) { return explode(',', $other); }, $others); $sum = 0; foreach ($others as $other) { foreach ($other as $number) { $is_valid = false; foreach ($compares as $compare) { if ($compare((int)$number) === true) { $is_valid = true; break; } } if (!$is_valid) { $sum += $number; echo sprintf('%u not in comparison list%s', $number, "\n"); } } } // sum it up echo $sum;