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 ;
?>
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Jan, 2022
Like Article
Save Article