This function works fine if I disable errors. But I have to solve them.
So I enabled the errors and found the following errors:
Notice: Undefined variable: retval in /home/content/79/9482579/html/gamelinkexchange.com/all/function.php on line 20
Notice: Use of undefined constant length – assumed ‘length’ in /home/content/79/9482579/html/gamelinkexchange.com/all/function.php on line 55
Here is my function:
function time_ago($date,$granularity=2) {
date_default_timezone_set('Asia/Calcutta');
$date = strtotime($date);
$difference = time() - $date;
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
foreach ($periods as $key => $value) {
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' '; /*error*/
$retval .= (($time > 1) ? $key.'s' : $key);
$granularity--;
}
if ($granularity == '0') { break; }
}
return $retval.' ago';
}
function gethours($str)
{
if(strpos($str, "decade"))
{
return 0;
}
else if(strpos($str, "year"))
{
return 0;
}
else if(strpos($str, "month"))
{
return 0;
}
else if(strpos($str, "week"))
{
return 0;
}
else if(strpos($str, "day"))
{
return 0;
}
else if(strpos($str, "hours"))
{
$strarr= explode(" ",$str);
$j=0; /*error*/
for($i=0;$i<$strarr.length;$i++)
{
if($strarr[$i]=="hours")
{
$j=$i-1;
}
}
return $strarr[$j];
}
else { return 1; }
}
This function is running very slow so I need to solve these errors. I tried solution provided in other pages of this website and other forums but nothing did help. Please provide a good solution which consumes less resources.
I need a solution to this. Because every entry has to pass time.
This is my first question, I am a newbie, please help. Thank You.
I couldn’t see you initialising your
$retvalanywhere. You should maybe have something like$retval = ''before you start appending anything to it, based on its value.About the other error, you’ve mistaken php with Java. In php you get the length of an array with
count($strarr)instead of$strarr.lengthUpdate
Instead of
you could simply use