PHP & MySQL | Tutorials

David Carr

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'.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.