Hi guys i have an array that is populated with dates
Array
(
[0] => 2012-04-04
[1] => 2012-04-06
[2] => 2012-04-06
[3] => 2012-04-06
[4] => 2012-04-06
[5] => 2012-04-06
[6] => 2012-04-06
[7] => 2012-04-11
[8] => 2012-04-12
[9] => 2012-04-12
[10] => 2012-04-13
[11] => 2012-04-13
[12] => 2012-04-13
[13] => 2012-04-13
[14] => 2012-04-13
[15] => 2012-04-13
[16] => 2012-04-13
)
How would I loop through the array and find the difference in days between items next to each other in array. For example i would want to echo out
difference between [0] and [1] is “2” days
difference between [1] and [2] is “0” days
🙂
Managed to get some output from the top answer however i only want it to display if there is a difference in date.
No output from this if statement though – UPDATED –
$count = count($datestack);
for ($i = 0; $i < $count - 1; $i++) {
$datetime1 = new DateTime($datestack[$i]);
$datetime2 = new DateTime($datestack[$i + 1]);
$interval = $datetime1->diff($datetime2);
if ($arr[$i] === $arr[$i+1]){
echo $interval->format('%R%a days');
}
}
What you need is DateTime::diff.
Example:
And you just need loop your array to do what you want.