How to calculate the average of the differences between timestamps in php?

0

Good afternoon, this is the first time I ask a question.

I have an array of data with timestamps. First of all I'm calculating the time difference between each of those brands. That calculation I'm doing it using the function --diff-- of the object --DateTime -

        $range = Array (
             '2018-01-18 18:52:31',
             '2018-01-18 18:54:30',
             '2018-01-18 18:57:42',
             '2018-01-18 19:05:02',
             '2018-01-18 19:10:01',
             '2018-01-18 19:15:05');
        $lastReg = null;
        $Tiempos = array();

        foreach ($range as  $log) {
            # code...
            if($index != 0){
                $datetime1 = new DateTime($log);
                $datetime2 = new DateTime($lastReg);
                $interval = $datetime1->diff($datetime2);
                array_push($Tiempos,$interval);
            }

        }

but now I want to calculate the average time between those differences.

It occurs to me to go through the $ Times I have been getting the value in seconds of each one and adding it up but I do not know how to do it ...

Thanks for your opinions.

    
asked by Thr Till 20.01.2018 в 18:04
source

1 answer

1

To calculate the average of a numerical array:

<?php

$num = [2, '2', 2];
$promedio = array_sum( $num ) / count( $num );

print_r( $promedio ); // Resultado: 2

+ info on array_sum()

To solve the error Object of class DateInterval could not be converted to string you have to convert it before with $interval->format('%a') :

Your code:

if($index != 0){
    $datetime1 = new DateTime($log->created_on);
    $datetime2 = new DateTime($lastReg->created_on);
    $interval = $datetime1->diff($datetime2);

    array_push($Tiempos, (int)$interval->format('%a'));
}

Online Demo

    
answered by 20.01.2018 в 18:10