Calculate the average between multiple dates in an array

2

I need to calculate an average not only between a start date and an end date, but on all dates present in an array to get an average result in days, hours, minutes, and seconds of how much X in X time such event is registered.

I have already developed a basis for this calculation but it does not seem to be correct, as we see in the example:

$dates = ['2015-05-10 12:00:00', '2015-05-11 12:00:00', '2015-05-12 12:00:00'];
$dates = array_map('strtotime', $dates);

for($count = count($dates), $result = 0, $i = 1; $i < $count; $i++)
{
    $result += $dates[$i-1] - $dates[$i];
}

$seconds = floor($result / $count);

$DTF = new DateTime("@0");
$DTT = new DateTime("@$seconds");
echo $DTF->diff($DTT)->format('%a dias, %h horas, %i minutos e %s segundos');

In the array, the difference between these 3 dates is exactly 24 hours, but the result since calculation is: 0 dias, 16 horas, 0 minutos e 0 segundos , what could be wrong?

    
asked by anonymous 13.06.2015 / 05:13

1 answer

2

Because at the end of the loop $result stored the two differences (24 + 24 = 48 hours) but divided by the number of indexes (3).

The correct one would be $seconds = floor($result / $count - 1) because although you have 3 dates, you only have 2 intervals between them.

    
13.06.2015 / 05:30