3v4l.org

run code in 300+ PHP versions simultaneously
<?php declare(strict_types=1); $data = [ '2020-07-14' => [ [ 'start_time' => '14:15:00', 'end_time' => '17:45:00', ],[ 'start_time' => '14:30:00', 'end_time' => '17:30:00', ],[ 'start_time' => '14:30:00', 'end_time' => '17:30:00', ], ], ]; function getSortedDays(array $days): array { return array_map(function (array $day) { array_multisort(array_column($day, 'start_time'), SORT_ASC, $day); return $day; }, $days); } function addTotalAttendedHours(array $days): array { $sortedDays = getSortedDays($days); $days = array_map(function (array $day) { $sum = (new DateTime())->setTimestamp(0); $previousEnd = null; foreach ($day as $time) { $currentStart = new DateTimeImmutable($time['start_time']); $currentEnd = new DateTimeImmutable($time['end_time']); if ($currentEnd < $previousEnd) continue; $sum->add($currentStart->diff($currentEnd)); if ($previousEnd !== null && $currentStart < $previousEnd) { $sum->sub($currentStart->diff($previousEnd)); } $previousEnd = $currentEnd; } $attendedSeconds = $sum->getTimestamp(); $day['total_attended_hours'] = sprintf( '%02u:%02u:%02u', $attendedSeconds / 60 / 60, ($attendedSeconds / 60) % 60, $attendedSeconds % 60 ); return $day; }, $sortedDays); return $days; } var_dump(addTotalAttendedHours($data));
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
array(1) { ["2020-07-14"]=> array(4) { [0]=> array(2) { ["start_time"]=> string(8) "14:15:00" ["end_time"]=> string(8) "17:45:00" } [1]=> array(2) { ["start_time"]=> string(8) "14:30:00" ["end_time"]=> string(8) "17:30:00" } [2]=> array(2) { ["start_time"]=> string(8) "14:30:00" ["end_time"]=> string(8) "17:30:00" } ["total_attended_hours"]=> string(8) "03:30:00" } }

preferences:
107.66 ms | 408 KiB | 5 Q