phptimehuman-readabletime-difference

Express time difference in a human readable format


On following function, I used 2 identical variables because inside is different language, I need help to replace this variable $periods[$j] .= "";

example:

function showdate($time)  
{  
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $periods2 = array("seconds", "minutes", "hours", "days", "weeks", "months", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");  
   
    $now = time();  
   
    $difference     = $now - $time;  
    $tense         = "ago";  
   
    for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)   
    {  
        $difference /= $lengths[$j];  
    }  
   
    $difference = round($difference);  
   
    if ($difference != 1)   
    {
        **/* In this case, I need to show this variable: $periods2 */**  
        $periods[$j] .= "";
    }  
   
    return "$difference $periods[$j] $tense";  
}

Solution

  • You can just write $periods[$j] = $periods2[$j], but I think making another variable is better.

    function showdate($time){  
        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $periods2 = array("seconds", "minutes", "hours", "days", "weeks", "months", "years", "decade");
        $lengths = array("60","60","24","7","4.35","12","10");  
    
        $now = time();  
        $difference = $now - $time;  
        $tense = "ago";
    
        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)     
            $difference /= $lengths[$j];  
    
        $difference = round($difference);  
        $pText = $periods[$j];
        if($difference>1) $pText = $periods2[$j];
        return "$difference $pText $tense";  
    }