Even though the answer has already been accepted, I thought I'd give my input nonetheless as I feel there are other options that are more robust and clear/easier to understand.
The Object-Oriented Approach
PHP has a collection of native objects specifically designed to handle date calculations, namely DateTime
and DateInterval
. making use of those objects will make the code easier to read and understand, which in turn means the code is easier to bug and more maintainable.
$dateArr = ['2017-08-25 06:27:00', '2017-08-25 07:38:00', '2017-08-25 08:34:00'];
$previousDate = '';
foreach($dateArr as $dateStr) {
$curDate = new DateTime($dateStr);
if(!empty($previousDate)) {
$diff = $previousDate->diff($curDate);
echo $diff->format('%i min').PHP_EOL;
}
$previousDate = $curDate;
}
This loop will output the following:
11 min
56 min
Of course, if you want to use this value for calculations, you'll need to do some extra manipulation to turn it into a numeric value type.
$min = $diff->format('%i');
if(is_numeric($min)) {
$min = (int) $min;
echo $min.' ('.gettype($min).')'.PHP_EOL;
}
else {
echo 'Oops, something went wrong :('.PHP_EOL; // good place to throw an exception, this echo is only for demo purposes
}
Outputs:
11 (integer)
56 (integer)
Using the DateTime
object will also allow you to catch badly formatted dates much more easily as it throws an exception instead of failing silently.
try {
$wrongDate = new DateTime('foobar');
echo $wrongDate->format('Y-m-d h:i:d').PHP_EOL;
}
catch(Exception $e) {
echo $e->getMessage().PHP_EOL; // the exception is caught
}
try {
$wrongToTime = strtotime('foobar');
echo $wrongToTome.PHP_EOL; // no exception si thrown and
// an undefined variable notice is thrown
}
catch(Exception $e) {
echo $e->getMessage().PHP_EOL;
}
Try it here!
Related Documentation