1

I have got the array of time in following format

$array = ('00:01:39','00:03:30','00:05:09','00:10:00','00:00:39','00:02:34','00:06:29','00:26:09','00:13:30','00:07:33');

I want the result for total as 01:17:12 and avg as 07:43

I tried by converting the time to strtotime,

and also tried using explode the given time using : and processing with it.

but could not get the expected outcome.

I want the simplest way to find the expected result.

Thanks in Advance.

logan Sarav
  • 781
  • 6
  • 27

2 Answers2

1

Try this:

// use example
$array = ['00:01:39','00:03:30','00:05:09','00:10:00','00:00:39','00:02:34','00:06:29','00:26:09','00:13:30','00:07:33'];
echo sum_time($array); # 01:17:12
echo avg_time($array); # 00:07:43

// functions
function calc_time(array $times) {
    $i = 0;
    foreach ($times as $time) {
        sscanf($time, '%d:%d:%d', $hour, $min, $sec);
        $i += $hour * 3600 + $min * 60 + $sec;
    }
    return $i;
}
function sum_time(array $times) {
    $i = calc_time($times);
    if ($h = floor($i / 3600)) $i %= 3600;
    if ($m = floor($i / 60)) $i %= 60;
    return sprintf('%02d:%02d:%02d', $h, $m, $i);
}
function avg_time(array $times) {
    $i = calc_time($times);
    $i = round($i / count($times));
    if ($h = floor($i / 3600)) $i %= 3600;
    if ($m = floor($i / 60)) $i %= 60;
    return sprintf('%02d:%02d:%02d', $h, $m, $i);
}

demo

Glavić
  • 42,781
  • 13
  • 77
  • 107
-1
$secs = strtotime($time1)+strtotime($time2);
$total = date("H:i:s",$secs);
$avg = date("H:i:s",$secs/2);