phptimetimestamptimeago

php time ago function


I just need a tip for a function that shows the time in ago format. On my database I have time stroed as timestamp. There are comments from users with date as timestamp. This date need to convert in time ago. I have a function but can't be recalled for every comment. It is working only 1 time for 1 comment. Can somebody help?

this is my function

function humanTiming($time)
{

$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
    31536000 => 'year',
    2592000 => 'month',
    604800 => 'week',
    86400 => 'day',
    3600 => 'hour',
    60 => 'minute',
    1 => 'second'
);

foreach ($tokens as $unit => $text) {
    if ($time < $unit) continue;
    $numberOfUnits = floor($time / $unit);
    return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}

}

Solution

  • This is probably a duplicate, but closing it won't show you what the problem in your code is.

    The return statement will immediately return the passed value from the function, and end execution of the function. So you will not ever get past the first run of your foreach loop. Probably what you want to do is something like this, where you build a string up in the loop, and then return it:

    $ret = "";
    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        $ret .= $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }
    return $ret;
    

    I didn't actually check if your code would work, but this is the crux of your problem.