PHP adding multiple times together

David Carr

PHP & MySQL Tutorials

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.

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.