Tutorials, PHP & MySQL

Adding multiple times together in an array with PHP

Adding times together can be complex when taking seconds, minutes and hours into account of multiple time calculations add an array into the mix its even more complicated! 

This small class below enables multiple times to be added together no matter how many they are.

The class:

class times_counter {

    private $hou = 0;
    private $min = 0;
    private $sec = 0;
    private $totaltime = '00:00:00';

    public function __construct($times){

            $length = sizeof($times);

            for($x=0; $x <= $length; $x++){
                    $split = explode(":", @$times[$x]); 
                    $this->hou += @$split[0];
                    $this->min += @$split[1];
                    $this->sec += @$split[2];

            $seconds = $this->sec % 60;
            $minutes = $this->sec / 60;
            $minutes = (integer)$minutes;
            $minutes += $this->min;
            $hours = $minutes / 60;
            $minutes = $minutes % 60;
            $hours = (integer)$hours;
            $hours += $this->hou % 24;
            $this->totaltime = $hours.":".$minutes.":".$seconds;

    public function get_total_time(){
        return $this->totaltime;


Usage Example:

$times = array(

$counter = new times_counter($times);
echo $counter->get_total_time();


This works by passing the constructer an array of times, then as long as the passed item is an array a for loop is performed to get the hours, minutes and seconds from all the times in the array. The time calculates are performed converting by 60 seconds and minutes appropriately and finally hours by 24.

A very handy class for taking the pain out of time calculations and 'just working'.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.