tags:

views:

289

answers:

3

I have a list of video segment durations I need to add up to get the total duration.

The series is like this:

  • 0:33
  • 4:30
  • 6:03
  • 2:10

...etc

I need to add up the minutes and seconds to get a total video duration.


Here's the modified function of my accepted answer:

function getTotalDuration ($durations) {
    $total = 0;
    foreach ($durations as $duration) {
        $duration = explode(':',$duration);
        $total += $duration[0] * 60;
        $total += $duration[1];
    }
    $mins = floor($total / 60);
    $secs = str_pad ( $total % 60, '2', '0', STR_PAD_LEFT);
    return $mins.':'.$secs;
}

Just made sure the output looks correct.

A: 

Convert all times to seconds, add them as integers, convert the sum back to minutes and seconds?

John at CashCommons
+3  A: 

Give this code a shot:

function getTotalDuration ($durations) {
    $total = 0;
    foreach ($durations as $duration) {
        $duration = explode(':',$duration);
        $total += $duration[0] * 60;
        $total += $duration[1];
    }
    $mins = $total / 60;
    $secs = $total % 60;
    return $mins.':'.$secs;
}
Travis
Thanks, I've added a couple things to pretty up the output, as shown in my edited question above.
Ian
+2  A: 

This stores the result in $seconds:

$seconds = 0;
foreach ($times as $time):
  list($m,$s) = explode(':',$time);  
  $seconds += $s + 60*$m;
endforeach;
Victor Nicollet