Calculate Total Time from Array of Times in PHP



The ‘strtotime’ function can be used to convert the given string into a time format. Let us see an example −

Example

 Live Demo

<?php
$time_arr = [
   '00:12:56', '10:11:12', '24:12:44',
   '50:51:52', '10:10:10'
];
$time = strtotime('00:00:00');
$total_time = 0;
foreach( $time_arr as $ele )
{
   $sec_time = strtotime($ele) - $time;
   $total_time = $total_time + $sec_time;
}
$hours = intval($total_time / 3600);
$total_time = $total_time - ($hours * 3600);
$min = intval($total_time / 60);
$sec = $total_time - ($min * 60);
print_r("The total time is :");
echo ("$hours:$min:$sec");
?>

Output

The total time is :-441915:-12:-58

An array that contains time format data is defined and the ‘strtotime´function is used to convert the string into a time format. The ‘foreach’ loop is used to iterate over the elements in the time format array and the elements are added.

The hours is calculated by dividing the value computed by 3600. The minutes is calculated by dividing the value computed by product of hours calculated and 3600. The seconds is calculated by dividing the value computer by product of minutes and 60. The total time computed is displayed on the console.

Updated on: 2020-07-02T06:48:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements