Userak Userak - 7 months ago 22
PHP Question

How to subtract array with dates to another array with date in php

I have two array with dates like start Date and end Date in want to get difference between both dates.

Start Date

Array
(
[0] => 2016-05-25
[1] => 2016-05-25
[2] => 2016-05-25
[3] => 2016-05-25
[4] => 2016-05-25
[5] => 2016-05-25
)


End Date

Array
(
[0] => 2016-05-28
[1] => 2016-05-28
[2] => 2016-05-28
[3] => 2016-05-28
[4] => 2016-05-28
[5] => 2016-05-28
)


Want Output

Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 3
[4] => 3
[5] => 3
)

Answer

Assuming your arrays are the same size, and the arrays names are $startDates and $endDates:

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   // we divide by 86400 since 86400 seconds per day
   $differences[] = (strtotime($endDates[$i]) - strtotime($startDates[$i])) / 86400;
}

You could also use DateTime objects with the diff method to get the difference between them (probably better idea, avoids possible divide by zero issues).

http://php.net/manual/en/datetime.diff.php

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   $date1 = new DateTime($endDates[$i]);
   $date2 = new DateTime($startDates[$i]);
   $interval = $date1->diff($date2);
   $differences[] = $interval->format('%a');
}

Edit: since you comment that it does not work:

$startDates = [
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25'
];

$endDates = [
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28'
];

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   // we divide by 86400 since 86400 seconds per day
   $differences[] = (strtotime($endDates[$i]) - strtotime($startDates[$i])) / 86400;
}

var_dump($differences);

Result:

array(5) {
  [0]=>
  int(3)
  [1]=>
  int(3)
  [2]=>
  int(3)
  [3]=>
  int(3)
  [4]=>
  int(3)
}

DateTime Method:

$startDates = [
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25'
];

$endDates = [
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28'
];

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   $date1 = new DateTime($endDates[$i]);
   $date2 = new DateTime($startDates[$i]);
   $interval = $date1->diff($date2);
   $differences[] = $interval->format('%a');
}

Result:

array(5) {
  [0]=>
  int(3)
  [1]=>
  int(3)
  [2]=>
  int(3)
  [3]=>
  int(3)
  [4]=>
  int(3)
}