Posted in Code Snippets, PHP

Sum n times

Adding two or more time in PHP is now easy. A small utility function can be use to sum multiple time in any format.

function add_time(array $times) {
    $seconds = 0;
    foreach ($times as $time)
    {
        list($hour,$minute,$second) = array_pad(explode(':', $time),3,null);
        $seconds += $hour*3600;
        $seconds += $minute*60;
        $seconds += $second;
    }
    $hours = floor($seconds/3600);
    $seconds -= $hours*3600;
    $minutes  = floor($seconds/60);
    $seconds -= $minutes*60;

    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

Example:

$times = ["10:20:00", "10:10:10"];
echo add_time($times); // 20:30:10

The input time can be in any format hhh:mm:ss or hh:mm format:

$times = ["100:20:00", "10:10"];
echo add_time($times); // 110:30:00

or even hh format:

$times = ["100:20:00", "10:10", "10"];
echo add_time($times); // 120:30:00

To display in mm:ss format use 0 placeholders for hh.

$times = ["00:10:10", "00:00:10"];
echo add_time($times); // 00:10:20
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s