0

I need to sum all values that date_diff function returns.

I have tried using array_sum(), but I get 0 as a result (as it is empty). The result should be 14.

$sql = "SELECT start_date, end_date FROM events";
  $result = $conn->query($sql);
  if ($result->num_rows > 0) {

   while($row = $result->fetch_assoc()) {
     $row["start_date"];   
     $row["end_date"];
     $start = date_create($row["start_date"]);
     $end = date_create($row["end_date"]);
     $fin=date_add($end, date_interval_create_from_date_string('1 days'));

     $diff=date_diff($start, $fin);
      echo $diff->format('%d days');

}

Code that I have provided works, but when I add array_sum() it constantly shows 0.

LF00
  • 27,015
  • 29
  • 156
  • 295
Ricky97
  • 79
  • 8

1 Answers1

1

You can create a base DateTime, and add all date_diff to it. Then calculate the sum date diff by subtracting the original base datetime.

$base_time = new DateTime();
$time = clone $base_time;
// begin foreach loop
...
$diff=date_diff($start, $fin);
$time->add($diff);
...
// end foreach loop
$sum_of_diff = $time->diff($base_time);

Nick
  • 138,499
  • 22
  • 57
  • 95
LF00
  • 27,015
  • 29
  • 156
  • 295