Search code examples
phpfunctiondivide-by-zero

How to remove division by zero from this function?


I use this php function to convert a numeric timestamp to something like "7 days ago", but a certain timestamp returns division by zero error, I don't know how to fix the function.

function timestamp_to_ago($timestamp){
    if(isset($timestamp) and $timestamp !=''){  
        $difference = time() - $timestamp;
        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $lengths = array("60","60","24","7","4.35","12","10");
        for($j = 0; $difference >= $lengths[$j]; $j++){
            $difference /= $lengths[$j]; // <<< line with problem
        }
        $difference = round($difference);
        if($difference != 1) $periods[$j].= "s";
        $text = "$difference $periods[$j] ago";
        return $text;
    }
}

// returns division by zero error
echo timestamp_to_ago(1135288800);

// doesn't return division by zero
echo timestamp_to_ago(1235288800);

The division by zero is triggered at this line $difference /= $lengths[$j]; but I don't know how to fix the function to avoid this error.


Solution

  • What happens, if it is more than a decade old?

        for($j = 0; isset($lengths[$j]) && $difference >= $lengths[$j]; $j++){
            $difference /= $lengths[$j]; // <<< line with problem
        }