-2

I have an array with dates

Array
(
    [0] => 2014-09-05
    [1] => 2014-09-09
    [2] => 2014-09-09
    [3] => 2014-09-11
    [4] => 2014-09-16
    [5] => 2014-09-18
    [6] => 2014-09-25
)

Look the interval between those dates are approximately 3 days.

How can I calculate this interval automatically?

4
  • 1
    Have you tried something ? Commented Jul 8, 2015 at 20:03
  • 1
    not yet. have no idea on how to do this Commented Jul 8, 2015 at 20:04
  • php.net/foreach php.net/strtotime Commented Jul 8, 2015 at 20:05
  • 1
    So where are we with this question ? Commented Jul 8, 2015 at 20:33

3 Answers 3

2

This should work for you:

Just loop through all of your dates and check if there is still a next date. If yes subtract both timestamps and add it to the $intervals array.

At the end just take the average of the intervals, which are in seconds, so you can divide it by 3600 * 24 to get the average day interval.

<?php

    $dates = [
        "2014-09-05",
        "2014-09-09",
        "2014-09-09",
        "2014-09-11",
        "2014-09-16",
        "2014-09-18",
        "2014-09-25",
        ];

    foreach($dates as $key => $date) {
        if(isset($dates[($key+1)]))
            $intervals[] = abs(strtotime($date) - strtotime($dates[($key+1)]));
    }

    $average = array_sum($intervals) / count($intervals);
    echo $average / (3600 * 24);

?>

output:

   _
3.33  //If you want you can round it up
Sign up to request clarification or add additional context in comments.

Comments

2

Generate an $difference_map array having differences between two dates from your input $dates array,

$difference_map = array_map(function($v, $k) use ($dates){
                    if($k == array_keys($dates)[0]) return;
                    $start = new DateTime($dates[$k-1]);
                    $end  = new DateTime($dates[$k]);
                    $diff = $start->diff($end);
                    return $diff->format('%R').$diff->days;
                }, $dates, array_keys($dates));

Then count average by,

$average = array_sum($difference_map)/(count($difference_map)-1);

If you take shown array as $dates in this script, $difference_map will look like,

array (size=7)
  0 => null
  1 => string '+4' (length=2)
  2 => string '+0' (length=2)
  3 => string '+2' (length=2)
  4 => string '+5' (length=2)
  5 => string '+2' (length=2)
  6 => string '+7' (length=2)

Finally, $average will be,

float 3.3333333333333

Comments

-1
Array
(
    [0] => 2014-09-05
    [1] => 2014-09-09
    [2] => 2014-09-09
    [3] => 2014-09-11
    [4] => 2014-09-16
    [5] => 2014-09-18
    [6] => 2014-09-25
)



 for($i=count(data);i>0;i--){
         echo date("d",strtotime($data[i]))-date("d",strtotime($data[i-1]))."<br/>";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.