Given an array containing the time in the hr: min: sec format. Problem - calculate the total time. If the total time is more than 24 hours, then the total time does not start at 0. It displays the total time. There are two ways to calculate the total time from an array.
Using the strtotime() function Using the explode() function Using function strtotime() : function strtotime() is used to convert string to time format. This function returns the time in h: m: s format.
Syntaxstrtotime (string)
Example 1 :This example reads values from an array and converts them to time format.
// Array containing the 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
) {
// Convert time to seconds
$timeinsec
=
strtotime
(
$element
) -
$sum
;
// Sum the time with the previous value
$totaltime
=
$totaltime
+
$timeinsec
;
}
// Totaltime is the sum of all
// time in seconds
// Hours are obtained by dividing
// total time since 3600
$h
=
intval
(
$totaltime
/ 3600);
$totaltime
=
$totaltime
- (
$h
* 3600);
// Minutes are obtained by dividing
// total time remaining since 60
$m
=
intval
(
$totaltime
/ 60);
// The rest is seconds
$s
=
$totaltime
- (
$m
* 60);
// Print result
echo
(
"$h: $m: $s"
);
?>
Exit:23:17 : 39
Using the function explode() : function explode() is used to split a string into an array.
Syntax array explode (separator, string, limit)
Example 2:This example reads values from an array and converts it to time format.
// 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;
// Data element loop
foreach
(
$arr
as
$element
):
// Space by delimiter:
$temp
=
explode
(
":"
,
$element
);
// Convert hours to seconds
// and add to the total
$total
+ = (int)
$temp
[0] * 3600;
// Convert minutes to seconds
// and add to the total
$total
+ = (int)
$temp
[1] * 60;
// Add seconds to total
$total
+ = (int)
$temp
[2];
endforeach
;
// Format seconds back to HH: MM: SS
$formatted
= sprintf (
’% 02d:% 02d:% 02d’
,
(
$total
/ 3600),
(
$total
/ 60% 60),
$total
% 60);
echo
$formatted
;
?>
Exit:23:07 : 39