Adding multiple times together in an array with PHP

David Carr

Tutorials PHP & MySQL

Table of Contents

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){
        
        if(is_array($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(
    '00:30:00',
    '01:15:00',
    '06:40:20',
    '02:05:16'
);

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

//outputs:
10:30:36

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

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.