Reputation: 11
i am fetching a data from my database according to client id. client id work time is different like:
00:15:00 00:20:00 etc.
this is not an array i make this as dynamic array
$time[] = $alltime;
result showing this:
Array
(
[0] => 00:20:00
[1] => 00:15:00
[2] => 00:20:00
[3] => 00:20:00
[4] => 00:55:00
[5] => 00:05:00
)
i want to sum all time. i tried many times and many way but output not showing according to time. please help
Upvotes: 1
Views: 661
Reputation: 147146
Here's one way to get the sum, using strtotime
to convert the times to seconds. Note that since strtotime
produces a timestamp relative to the Unix Epoch, you need to subtract the start of the day (strtotime('00:00')
) from each value to get the number of seconds in the time:
$time = array
(
'00:20:00',
'00:15:00',
'00:20:00',
'00:20:00',
'00:55:00',
'00:05:00'
);
$time_in_secs = array_map(function ($v) { return strtotime($v) - strtotime('00:00'); }, $time);
$total_time = array_sum($time_in_secs);
$hours = floor($total_time / 3600);
$minutes = floor(($total_time % 3600) / 60);
$seconds = $total_time % 60;
echo "Total time is "
. str_pad($hours, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($minutes, 2, '0', STR_PAD_LEFT)
. ":" . str_pad($seconds, 2, '0', STR_PAD_LEFT) . "\n";
Output:
Total time is 02:15:00
You could also simplify the code by using array_reduce
to compute $total_time
instead of array_map
and array_sum
:
$total_time = array_reduce($time, function ($c, $v) { return $c + strtotime($v) - strtotime('00:00'); }, 0);
Upvotes: 2