PHP & MySQL | Tutorials

David Carr

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.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.