PHP program to calculate the total time given an array of times

In PHP, you can calculate the total time from an array of time strings by converting each time to seconds, summing them up, and converting back to HH:MM:SS format. The key is to parse time strings correctly and handle the arithmetic properly.

Example

Here's how to sum an array of time strings ?

<?php
$time_arr = [
    '00:12:56', '10:11:12', '02:12:44',
    '01:51:52', '10:10:10'
];

$total_seconds = 0;

foreach($time_arr as $time) {
    $parts = explode(':', $time);
    $hours = intval($parts[0]);
    $minutes = intval($parts[1]);
    $seconds = intval($parts[2]);
    
    $total_seconds += ($hours * 3600) + ($minutes * 60) + $seconds;
}

$final_hours = intval($total_seconds / 3600);
$remaining_seconds = $total_seconds % 3600;
$final_minutes = intval($remaining_seconds / 60);
$final_seconds = $remaining_seconds % 60;

printf("Total time: %02d:%02d:%02d
", $final_hours, $final_minutes, $final_seconds); ?>
Total time: 24:38:54

How It Works

The solution breaks down each time string using explode(':') to separate hours, minutes, and seconds. Each component is converted to seconds and added to the running total. Finally, the total seconds are converted back to HH:MM:SS format using division and modulo operations.

Alternative Using DateTime

For more complex time calculations, you can use PHP's DateTime class ?

<?php
$time_arr = ['02:30:45', '01:15:30', '00:45:15'];
$total_seconds = 0;

foreach($time_arr as $time) {
    $datetime = DateTime::createFromFormat('H:i:s', $time);
    $total_seconds += $datetime->format('H') * 3600 + 
                     $datetime->format('i') * 60 + 
                     $datetime->format('s');
}

$hours = floor($total_seconds / 3600);
$minutes = floor(($total_seconds % 3600) / 60);
$seconds = $total_seconds % 60;

echo sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
?>
04:31:30

Conclusion

Use explode() for simple time string parsing or DateTime for more robust time handling. Always convert to seconds for arithmetic operations, then format back to HH:MM:SS for display.

Updated on: 2026-03-15T09:04:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements