Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Adding multiple times together in an array with PHP

David Carr

PHP & MySQL Tutorials

  • The class:
  • Usage Example:
  • 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'.

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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