Martin AJ Martin AJ - 4 months ago 9
PHP Question

Should I store the result of an function into an array?

I have a function like this:

function time_elapsed_string($ptime)
{
$date_time = strtotime("1348-10-10 04:30:01") + $ptime;
$year = date("Y",$date_time);
$month = date("m",$date_time);
$day = date("d",$date_time);
$time = date("H:i:s",$date_time);

$etime = time() - $ptime + 1;

$a = array( 31536000 => 'year',
2592000 => 'month',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);

foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
// EX:
return array('date' => $day.'-'.$month.'-'.$year, // 2016-02-20
'time' => $time, // 03:30:04
'difference' => $r . ' ' . $str . ' ago' // 2 month ago
);
}
}
}


And I use it like this:

$ptime = 1470692661;
$html = '<span title="date: '.time_elapsed_string($ptime)['date'].' time: '.time_elapsed_string($ptime)['time'].'">in '.time_elapsed_string($ptime)['difference'].'<span>';


As you see, I'm using of that function's result like this:

time_elapsed_string($ptime)['date']
ime_elapsed_string($ptime)['time']
time_elapsed_string($ptime)['difference']


In fact I'm calling that function every time I need one of its results. Is that right? Or should I call it once and store it into an array?

Note: My code works as well.

Answer

Counting time elapsed since some date/time like this is mauvais ton.

DateTime has been available since PHP 5.2.0 and tonns of people underestimate it. Why don't you use this instead of loops and ifs?

$create_time = "2016-08-02 12:35:04";
$current_time="2016-08-02 16:16:02";

$dtCurrent = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
// to use current timestamp, use the following:
//$dtCurrent = new DateTime();
$dtCreate = DateTime::createFromFormat('Y-m-d H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);

Now, you can format the result however you want:

$interval = $diff->format("%h hours %i minutes %s seconds");

This will give a clean 3 hours 40 minutes 58 seconds without any arrays, which is better.

UPDATE

There is a general solution to get hours / minutes / seconds via regex:

$interval = $diff->format("%y years %m months %d days %h hours %i minutes %s seconds");

// now remove zero values
$interval = preg_replace('/(^0| 0) (years|months|days|hours|minutes|seconds)/', '', $interval);

UPDATE 2

As of your comment:

Look, I want to use your approach .. but I really cannot implement it .. Actually I need three things: time, date, difference ..! But your approach doesn't give me them..

Well, we already know how to get the difference, it's the $interval variable described above.

To get time and date, you can get it from the $dtCreate variable by, again, using format:

$time = $dtCreate->format('H:i:s');
$date = $dtCreate->format('d-m-Y');