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.
- Using strtotime() function
- 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
$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 ) {
$timeinsec = strtotime ( $element ) - $sum ;
$totaltime = $totaltime + $timeinsec ;
}
$h = intval ( $totaltime / 3600);
$totaltime = $totaltime - ( $h * 3600);
$m = intval ( $totaltime / 60);
$s = $totaltime - ( $m * 60);
echo (" $h : $m : $s ");
?>
|
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
$arr = [
'00:04:35' , '00:02:06' , '01:09:12' ,
'09:19:04' , '00:17:49' , '02:03:59' ,
'10:10:54'
];
$total = 0;
foreach ( $arr as $element ):
$temp = explode (":", $element );
$total += (int) $temp [0] * 3600;
$total += (int) $temp [1] * 60;
$total += (int) $temp [2];
endforeach ;
$formatted = sprintf( '%02d:%02d:%02d' ,
( $total / 3600),
( $total / 60 % 60),
$total % 60);
echo $formatted ;
?>
|
Last Updated :
19 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...