How to sum N number of time (HH:MM Format)?

I am using the following sample code to calculate sum of two different time values. Now I want to get the sum of N number of time values.

// numbers for testing
$o="12:59";
$p="0:58";

// display for testing
echo "$o<br />";
echo "$p<br />";
echo AddPlayTime($o,$p);

// FUNCTION - ADD HOURS and MINUTES
function AddPlayTime ($oldPlayTime, $PlayTimeToAdd) {
  $old=explode(":",$oldPlayTime);
  $play=explode(":",$PlayTimeToAdd);

  $hours=$old[0]+$play[0];
  $minutes=$old[1]+$play[1];

  if($minutes > 59){
    $minutes=$minutes-60;
    $hours++;
  }

  if($minutes < 10){
    $minutes = "0".$minutes;
  }

  if($minutes == 0){
    $minutes = "00";
  }

  $sum=$hours.":".$minutes;
  return $sum;
}

this should do what you are looking for:

$times is the array of times and you can add how many time you want

$times = array();

$times[] = "12:59";
$times[] = "0:58";
$times[] = "0:02";

// pass the array to the function
echo AddPlayTime($times);

function AddPlayTime($times) {
    $minutes = 0; //declare minutes either it gives Notice: Undefined variable
    // loop throught all the times
    foreach ($times as $time) {
        list($hour, $minute) = explode(':', $time);
        $minutes += $hour * 60;
        $minutes += $minute;
    }

    $hours = floor($minutes / 60);
    $minutes -= $hours * 60;

    // returns the time already formatted
    return sprintf('%02d:%02d', $hours, $minutes);
}

EDIT

I edited the code with the right names of the variables. It is more correct now.

hope this helps :-)


Here is an function that will sum all your time values in format HH:MM:

function sum_time() {
    $i = 0;
    foreach (func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }
    if ($h = floor($i / 60)) {
        $i %= 60;
    }
    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06

demo