0

I'm iterating through an array of objects and each object has a time attribution. As I iterate through the array I want to calculate the total time. Not sure how to add minutes in the time. Please refer to this screenshot Only hours are getting added. Code to add the time is written below

$total_human_readable_time += humanReadableTime($total_workhours);

Function humanReadableTime is defined below

function humanReadableTime($time) {
 $time = abs($time);
 $hours = floor($time);
 $minutes = ceil(($time - floor($time)) * 60);
 if ($minutes < 10) {
  $minutes = "0$minutes";
 }
 return $hours . ":" . $minutes;
}
Vasu
  • 69
  • 1
  • 1
  • 7
  • You should look into [DateTime](http://php.net/manual/en/class.datetime.php) and [DateInterval](http://php.net/manual/en/class.dateinterval.php). You're not going to be able to perform simple math on strings like "4:25". – Patrick Q May 15 '18 at 20:52
  • Possible duplicate of [How to create a DateInterval from a time string](https://stackoverflow.com/questions/21742329/how-to-create-a-dateinterval-from-a-time-string) – Patrick Q May 15 '18 at 20:56
  • 1
    Are you aware that version 5.3 of PHP reached the end of it's life (no longer supported) August 2014? Version 5.6 goes end of life (along with 7.0) in December this year. At the very least you should now be using 5.6 – SpacePhoenix May 16 '18 at 00:19

1 Answers1

0

If your humanReadableTime function is already doing what you want it to, it looks like all you should have to do is not call it as you iterate, but instead just add up the unformatted values and then call it once at the end.

foreach($objects as $object) {
    // something that gives you $total_workhours
    $total_time += $total_workhours;
}
$total_human_readable_time = humanReadableTime($total_time);
Don't Panic
  • 41,125
  • 10
  • 61
  • 80