Get the number of days from given dates in php array

I am trying to get the number of days from the first date to the second date, and then from the second date to the third date, etc. I have an array like this

$dates = array(
    2016 - 02 - 01,
    2016 - 03 - 01,
    2016 - 04 - 01,
    2016 - 05 - 01,
    2016 - 06 - 01,
    2016 - 07 - 01,
    2016 - 09 - 01,
    2016 - 11 - 01,
    2016 - 12 - 01,
    2017 - 01 - 01,
    2017 - 12 - 01
);

I want to get the number of days from 2016-02-01 to 2016-03-01, and then from 2016-03-01 to 2016-04-01 and so on, if you notice that there are some spaces in the dates, as in them Jump for more than 1 month. And I want it in such an array

array()(
    [0] => 0,
    [1] => 30,
    [2] => 60
    //so on ...
) 

This is how I do it, but I get errors such as uninitialized string offset, and I assume that I am doing wrong, most likely

public  function rangeDates()
{
    $dates = array(
        '2016-02-01',
        '2016-03-01',
        '2016-04-01',
        '2016-05-01',
        '2016-06-01',
        '2016-07-01',
        '2016-09-01',
        '2016-11-01',
        '2016-12-01',
        '2017-01-01',
        '2017-12-01'
    );
    $datez = array();
    $index = 0;
    $indexone = 1;
    foreach($dates as $date)
    {
        $datez = round(abs(strtotime($date[$index]) - strtotime($date[$indexone])) / 86400);
        $index++;
        $indexone++;
    }

    echo $datez;
}

Dates in string format , additional information that I forgot to mention is that days should be added, for example, if we take only years

array(11) (
  [0] => (int) 0
  [1] => (int) 365
  [2] => (int) 730
  [3] => (int) 1095
  [4] => (int) 1460
  [5] => (int) 1825
  [6] => (int) 2190
  [7] => (int) 2555
  [8] => (int) 2920
  [9] => (int) 3285
  [10] => (int) 3650
+4
1

, , , . . .

$dates = array(
    "2016-02-01",
    "2016-03-01",
    "2016-04-01",
    "2016-05-01",
    "2016-06-01",
    "2016-07-01",
    "2016-09-01",
    "2016-11-01",
    "2016-12-01",
    "2017-01-01",
    "2017-12-01"
);

$datez = array();
$date = array();
$datez[] = 0;

for($i = 1; $i < count($dates) - 1; $i++){
    $start_date = $dates[$i-1];
    $end_Date = $dates[$i];

    $date1 = new DateTime($start_date);
    $date2 = new DateTime($end_Date);
    $interval = $date1->diff($date2);

    $date[]  = $interval->days;
    $datez[] = array_sum($date);
}

print_r($date);
print_r($datez);

-

+5

Source: https://habr.com/ru/post/1656778/


All Articles