Tutorials, PHP & MySQL

PHP adding multiple times together

Working with dates and times can be tricky unless you use some handy built in functions, I found myself needing to do a few different time calculations that had me stumped for awhile (head down in shame!).

I have a series of times in the format of hh:mm:ss that I needed to add together to get a total. I first tried adding them all together of course the result was wrong so I took to Google trying to find a quick solution to my problem, as this can be much quicker at times.

I found lots of results most of which had line after line of code! way too much for such a simple task, I wanted something simple then I realised as I already had the times in a time format I can make use of strtotime which will convert the time from hours, minutes and seconds to seconds then I can add those seconds together.

Here is my very simple code in action:

$total = strtotime($r->mon) + strtotime($r->tue) + strtotime($r->wen) + strtotime($r->thu) + strtotime($r->fri);

The strtotime function expects a data to be passed you can also pass just a time which is what I have done in this case, then to show the total time I used date combined with strtotime:

date('H:i', $total)

A very simple and easy to expand solution.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.