Average hours PHP


I want to add and take an average of a few hours.

$cadena = '00:09:00,00:09:00,00:09:00,00:09:00,00:09:00';
$arr = explode(",",$cadena);
$total = strtotime('00:00:00');

for($i = 0; $i<count($arr);$i++)
  $total = $total + strtotime($arr[$i]);

$total = $total / count($arr);
echo date('H:i:s',$total);

This brings me back 05:45:00 and I waited 00:09:00. What was the mistake: (

asked by Alberto Siurob 14.02.2017 в 01:31

3 answers


You could do something like this:


$cadena    = '00:09:00,00:09:00,00:09:00,00:09:00,00:09:00';
$arreglo   = explode(",", $cadena);
$resultado = 0;

foreach($arreglo AS $tiempo)
    $resultado += strtotime($tiempo) - strtotime("TODAY") . "\n";

$resultado = $resultado / count($arreglo);

echo gmdate("H:i:s", $resultado);





answered by 14.02.2017 / 01:54

When you call strtotime without passing a date, it assumes the current date, and today's timestamp plus nine minutes is not the same as the timestamp of T = 0 plus nine minutes.

In particular, timestamp 0 occurred on December 31, 1969 at 9:00 p.m., so there is an implied lag of three hours in any strtotime. That has such strange consequences that

echo date('H:i:s',strtotime('00:00:00')+strtotime('00:09:00'));



In your case, you are initializing the total with a non-zero value, so the average of that sum is meaningless.

Ivan Botero's solution solves your problem because it initializes the total explicitly to zero, and in each iteration of the loop removes the time delta between the current date and the initial timestamp of the universe.

answered by 14.02.2017 в 02:18

If you want to add here, this I hope it helps





echo "<br>".$total;
answered by 14.02.2017 в 02:26