Monday, November 18, 2024
Google search engine
HomeLanguagesHow to calculate total time of an array in PHP ?

How to calculate total time of an array in PHP ?

Given an array containing the time in hr:min:sec format. The task is to calculate the total time. If the total time is greater then 24 hours then the total time will not start with 0. It will display the total time. There are two ways to calculate the total time from the array. 
 

  1. Using strtotime() function
  2. Using explode() function

Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format.
Syntax 
 

strtotime( string )

Example 1: This example reads the values from the array and converts it into the time format.
 

php




<?php
 
// Array containing time in string format
$time = [
    '00:04:35', '00:02:06', '01:09:12',
    '09:19:04', '00:17:49', '02:13:59',
    '10:10:54'
];
 
$sum = strtotime('00:00:00');
 
$totaltime = 0;
 
foreach( $time as $element ) {
     
    // Converting the time into seconds
    $timeinsec = strtotime($element) - $sum;
     
    // Sum the time with previous value
    $totaltime = $totaltime + $timeinsec;
}
 
// Totaltime is the summation of all
// time in seconds
 
// Hours is obtained by dividing
// totaltime with 3600
$h = intval($totaltime / 3600);
 
$totaltime = $totaltime - ($h * 3600);
 
// Minutes is obtained by dividing
// remaining total time with 60
$m = intval($totaltime / 60);
 
// Remaining value is seconds
$s = $totaltime - ($m * 60);
 
// Printing the result
echo ("$h:$m:$s");
 
?>


Output: 

23:17:39

 

Using explode() function: The explode() function is used to break a string into an array.
Syntax 
 

array explode( separator, string, limit )

Example 2: This example reads the values from an array and converts it into the time format.
 

php




<?php
 
// Declare an array containing times
$arr = [
    '00:04:35', '00:02:06', '01:09:12',
    '09:19:04', '00:17:49', '02:03:59',
    '10:10:54'
];
 
$total = 0;
 
// Loop the data items
foreach( $arr as $element):
     
    // Explode by separator :
    $temp = explode(":", $element);
     
    // Convert the hours into seconds
    // and add to total
    $total+= (int) $temp[0] * 3600;
     
    // Convert the minutes to seconds
    // and add to total
    $total+= (int) $temp[1] * 60;
     
    // Add the seconds to total
    $total+= (int) $temp[2];
endforeach;
 
// Format the seconds back into HH:MM:SS
$formatted = sprintf('%02d:%02d:%02d',
                ($total / 3600),
                ($total / 60 % 60),
                $total % 60);
 
echo $formatted;
 
?>


Output: 

23:07:39

 

RELATED ARTICLES

Most Popular

Recent Comments