Stuck trying to figure out the best algorithm here. I have this simple function where the input is seconds:
function strTime($s) {
$d = intval($s/86400);
$s -= $d*86400;
$h = intval($s/3600);
$s -= $h*3600;
$m = intval($s/60);
$s -= $m*60;
if ($d) $str = $d . 'day ';
if ($h) $str .= $h . 'hr ';
if ($m) $str .= $m . 'min ';
if ($s) $str .= $s . 'sec';
return $str;
}
I like this because it will only show what is needed. For example if the seconds are at 3600 the output of this function will be “1 hr”.
My issue is that in some cases the seconds will be 0 (when they start using the product). How can I show 0 secs in those cases but in other times like the example above I don’t want it to say “1 hr 0 sec”. I’m struggling to think of a way to do this.
Just check to see if the string is still empty after all four if statements have run. You also have an error where you append data to an uninitiated string if
$dis 0; you should instead initialize $str explicitly and make all fourifstatements append.That is, “if we have seconds, or the string is still empty, show the number of seconds”.
You should be expanding on each
ifstatements to allow for pluralization as well, and possibly ignoring only the leading/trailing zeros instead of all zeros.What I mean is that these examples look weird:
You probably want the zeros for the intermediate units: