VPS business hosting starting at $29.95/24/7 premium technical support

How to add colon separated hours in PHP using explode function twice?

Problem Statement

Tracking hours for multiple days are available in HH:MM:SS format separated by tab element. Add all the time to show total hours worked/tracked.

<?php
$a="03:23:28	03:58:54	00:00:00	03:10:49	02:17:33	03:56:38	02:18:23	06:15:42	00:00:00	00:00:00	06:04:51	07:41:09	03:23:15	06:12:59	03:51:27	00:00:00	04:30:06	05:00:23	00:00:00	04:34:25	05:17:02	01:36:21	00:00:00	03:53:20	06:30:52	06:21:47	04:54:16	03:22:28	03:10:35	00:00:00	06:37:11	02:14:22	03:06:49	03:05:44	02:35:54	04:03:22	00:00:00
";
#$a="04:05:21	06:25:39	03:02:36	04:01:17	03:03:21	02:00:36	04:21:54	04:21:35	00:00:00	00:00:00	03:39:21	04:19:17	03:08:14	01:44:48	03:28:11	00:00:00	03:05:53	03:05:34	00:00:00	02:09:17	05:01:13	01:02:20	00:00:00	04:30:51	06:03:49	06:36:35	02:14:01	03:06:38	04:02:09	00:00:00	02:34:29	03:36:30	05:10:17	06:46:19	07:48:08	09:13:34	00:00:00
#";
$a="07:28:49	10:24:33	03:02:36	07:12:06	05:20:54	05:57:14	06:40:17	10:37:17	00:00:00	00:00:00	09:44:12	12:00:26	06:31:29	07:57:47	07:19:38	00:00:00	07:35:59	08:05:57	00:00:00	06:43:42	10:18:15	02:38:41	00:00:00	08:24:11	12:34:41	12:58:22	07:08:17	06:29:06	07:12:44	00:00:00	09:11:40	05:50:52	08:17:06	09:52:03	10:24:02	13:16:56	00:00:00
";
$f=explode("\t",$a);
$th=$tm=$ts=0;
foreach($f as $ele){
	
	$ht=explode(":",$ele);
	$hours=intval($ht[0]);
	$minutes=intval($ht[1]);
	$seconds=intval($ht[2]);
	$th+=$hours;
	$tm+=$minutes;
	$ts+=$seconds;
}
$mm=intval($ts/60);
$ts=$ts%60;
$tm+=$mm;
$hh=intval($tm/60);
$tm=$tm%60;
$th+=$hh;

echo "$th:$tm:$ts";
?>

Author: Harshvardhan Malpani

PHP Developer based in New Delhi, India. Working as a freelance web developer providing server deployment, website development and maintenance services.

Leave a Reply

Your email address will not be published. Required fields are marked *