I also forgot to mention that leveraging zero as "loose false" and non-zero as "loose true" simplified the code a bit too. MOST of the time if you're sure the value is numeric, there's no real reason to say ==0 or !=0 in loosely typed languages. Just if() it.
Here's what I meant by using define, it's PHP 7 / newer only but that should be a non issue as of two years ago.
// defining Arrays is new as of PHP 7
define('DATE_WORDS', [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second'
]);
function date_CalculateDifference($incoming) {
// calculates the difference between DateTime objects
$interval = date_diff(
empty($incoming['end']) ? date() : date_create($incomping['end']),
date_create($incoming['start'])
);
foreach ($interval as $k => $v) {
if ($v) return pluralize($v, DATE_WORDS[$k]) . (
$interval->invert ? ' ago' : ''
);
}
return 'now'; // they were all zero
} // date_calcDifference
function pluralize($val = 0, $text) {
return $val . ' ' . $text . ($val == 1 ? '' : 's';
} // pluralize
Why do this? First off it gets excess code out of the logic of your function. Second you might want/need it elsewhere so you only have one copy. Third it makes it static in memory so that every time you call your function it doesn't get recreated / take extra processing time. Finally it gives you a nice central spot to change it across all functions you might need it for when it comes to things like localization.
Basically if you were to call your difference function more than once, putting a static value into define (or a static on an object) uses less memory and runs faster, and requires less garbage collection.