AR Bhuiyan
AR Bhuiyan

Reputation: 21

php sum time with variable in while loop

php sum variable in while loop I have to "sum" variable's values in while, here us my example :

while($row = mysql_fetch_array($result)){
  $working_hour= $row[working_hour];
}

The code above will output if I put echo $working_hour; for example: 01:00:03, 01:03:04, 01:10:15 I want something like : sum($working_hour) or array_sum($working_hour) to count all the results of while loop. So, that i want to count: 01:00:03, 01:03:04, 01:10:15= 03:13:22 I try this way :

$total_working_hour=’00:00:00’;
while($row = mysql_fetch_array($result)){
  $working_hour= $row[working_hour];
  $total_working_hour+= $working_hour;
}

Echo $total_working_hour;

The code above provide output as:

03

How can I do it with php? Thanks

Upvotes: 1

Views: 1497

Answers (4)

jiGL
jiGL

Reputation: 175

If the format in your example is fix, you can work with DateTime-Object and Date-Interval as well like this... (for further information to DateInterval, have a look at the PHP-Docu)

    $dt = new \DateTime('00:00:00');
    foreach ($dbRows as $row) {

        $time = $row['working_hour'];
        $timeSplit = explode(':', $time);
        $interval = new \DateInterval(
            'P0Y0DT'.$timeSplit[0].'H'.
            $timeSplit[1].'M'.$timeSplit[2].'S'
        );
        $dt->add($interval);
    }

    echo $dt->format('H:i:s'); // Output: 03:13:22

Upvotes: 0

Sherif
Sherif

Reputation: 11943

The value of $row["working_hour"] is clearly a string. So saying something like "01:00:03" + "01:03:04" clearly makes no sense. PHP assumes that what you meant to do was cast the strings to integers first and then add them together. The result of that is not what you're actually after.

Instead, you want to convert a string like "01:00:03" to an normalized integer value, like number of seconds, that can be added together and then converted back to a string value.

So to get the normalized value of the string as an integer in seconds you need a function like this...

function convertStringToNumSeconds($string) {
    list($hours, $minutes, $seconds) = explode(":", $string, 3);
    $totalSeconds = 0;
    $totalSeconds += $hours * 3600; // There are 3600 seconds in an hour
    $totalSeconds += $minutes * 60; // There are 60 seconds in a minute
    $totalSeconds += $seconds; // There is 1 second in a second
    return $totalSeconds;
}

Then to convert the seconds back to a formatted string you can do the opposite...

function secondsToString($seconds) {
    $hours = (int) floor($seconds / 3600);
    $seconds -= $hours * 3600;
    $minutes = (int) floor($seconds / 60);
    $seconds -= $minutes * 60;
    return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}

Now in your loop you can actually do something like this...

$totalWork = 0;
while($row = mysql_fetch_array($result)){
  $totalWork += convertStringToNumSeconds($row["working_hour"]);
}
echo secondsToString($totalWork); // You should get your expected result

Upvotes: 0

SattyamBhatt
SattyamBhatt

Reputation: 328

   $hours=0;$min=0;$sec=0;
    while($row = mysql_fetch_array($result)){
      $working_hour= $row[working_hour];
        $arr=explode(':',$working_hour);
        $hours=$hours+$arr[0];
        $min=$min+$arr[1];
       if($min>60){$hours++;$min=$min-60;}
        $sec=$sec+$arr[2];
        if($sec>60){$min++;$sec=$sec-60;}
    }
    echo 'Total working hours='.$hours.':'.$min.':'.$sec;

Upvotes: 1

ptvty
ptvty

Reputation: 5664

I used the answer here (how to sum the array time) and created the following function:

  function addTime($a, $b) {
    $array = [$a, $b];
    $totalTimeSecs = 0;
    foreach ($array as $time) { // Loop outer array
      list($hours,$mins,$secs) = explode(':',$time); // Split into H:m:s
      $totalTimeSecs += (int) ltrim($secs,'0'); // Add seconds to total
      $totalTimeSecs += ((int) ltrim($mins,'0')) * 60; // Add minutes to total
      $totalTimeSecs += ((int) ltrim($hours,'0')) * 3600; // Add hours to total
    }

    $hours = str_pad(floor($totalTimeSecs / 3600),2,'0',STR_PAD_LEFT);
    $mins = str_pad(floor(($totalTimeSecs % 3600) / 60),2,'0',STR_PAD_LEFT);
    $secs = str_pad($totalTimeSecs % 60,2,'0',STR_PAD_LEFT);
    return "$hours:$mins:$secs";
  }

So you can use this and replace

$total_working_hour+= $working_hour;

with

$total_working_hour = addTime($total_working_hour, $working_hour);

Upvotes: 0

Related Questions