A switch to display either one or the other string dependend on a counter
static public plural ( integer $count, string $many, string $one, string $zero = '' ) : string | ||
$count | integer | The counter |
$many | string | The string to be displayed for a counter > 1 |
$one | string | The string to be displayed for a counter == 1 |
$zero | string | The string to be displayed for a counter == 0 |
return | string | The string |
public static function unix2exactrelative($date, $show_weeks = TRUE, $format = "\\o\n F j, Y") { $diff = time() - $date; if ($diff < 60) { return $diff . " " . str::plural('second', $diff) . " ago"; } $diff = round($diff / 60); if ($diff < 60) { return $diff . " " . str::plural('minute', $diff) . " ago"; } $diff = round($diff / 60); if ($diff < 24) { return $diff . " " . str::plural('hour', $diff) . " ago"; } $diff = round($diff / 24); if ($diff < 7) { return $diff . " " . str::plural('day', $diff) . " ago"; } $diff = round($diff / 7); if ($diff < 4 && $show_weeks) { return $diff . " " . str::plural('week', $diff) . " ago"; } return date($format, $date); }
/** * Formats a second into years, months, days, hours, minutes, seconds. * * Example: * format::seconds(65) returns "1 minute, 5 seconds" * * @param int number of seconds * @return string formatted seconds */ public static function seconds($seconds) { list($years, $months, $days, $hours, $minutes, $seconds) = explode(":", gmdate("Y:n:j:G:i:s", $seconds)); $years -= 1970; $months--; $days--; $parts = array(); if ($years > 0) { $parts[] = $years . " " . str::plural("year", $years); } if ($months > 0) { $parts[] = $months . " " . str::plural("month", $months); } if ($days > 0) { $parts[] = $days . " " . str::plural("day", $days); } if ($hours > 0) { $parts[] = $hours . " " . str::plural("hour", $hours); } if ($minutes > 0) { $parts[] = sprintf("%d", $minutes) . " " . str::plural("minute", $minutes); } if ($seconds > 0) { $parts[] = sprintf("%d", $seconds) . " " . str::plural("second", $seconds); } return implode(", ", $parts); }
public function test_plural() { // 0 $this->assertEquals('zero', str::plural(0, 'many', 'one', 'zero')); // 1 $this->assertEquals('one', str::plural(1, 'many', 'one', 'zero')); // 2 $this->assertEquals('many', str::plural(2, 'many', 'one', 'zero')); // 0 without zero $this->assertEquals('many', str::plural(0, 'many', 'one')); }