Max Liberman

Useful PHP Functions

Here is a collection of simple PHP functions I frequently find useful. They are free to use, copy and adapt with no restrictions; credit is appreciated but not required.

Singular and Plural

This function returns the singular or plural form of a word, according to the value of the given number. $singular defaults to an empty string, and $plural to $singular plus “s”. This means you can use, for example, $min . ' minute' . plural($min) or plural($count, 'person', 'people') – no need to settle for careless-looking output like “1 minutes”.

function plural($n, $singular = '', $plural = null) {
	if ($plural === null) $plural = $singular . 's';
	return ($n == 1) ? $singular : $plural;
}

UTF-8 Encoding

This function gets the UTF-8 representation of one or more Unicode characters. It accepts any number of arguments – each is either a Unicode codepoint or an array of codepoints. The resulting UTF-8 representations are strung together. Note that codepoints must be actual numbers, not hexadecimal strings (198, '198' and 0xc6 are fine, but 'c6' is not).

function utf8() {
	$utf8 = '';
	foreach (func_get_args() as $c) {
		if (is_array($c)) foreach ($c as $cp) $utf8 .= utf8($cp);
		else if ($c < 0x80) $utf8 .= chr($c);
		else if ($c < 0x800) $utf8 .= chr($c >> 6 | 0xc0) . chr($c & 0x3f | 0x80);
		else if ($c < 0x10000) $utf8 .= chr($c >> 12 | 0xe0) . chr($c >> 6 & 0x3f | 0x80) . chr($c & 0x3f | 0x80);
		else $utf8 .= chr($c >> 18 | 0xf0) . chr($c >> 12 & 0x3f | 0x80) . chr($c >> 6 & 0x3f | 0x80) . chr($c & 0x3f | 0x80);
	}
	return $utf8;
}

Ordinal Suffixes

This function returns a number with the appropriate ordinal suffix appended (e.g., “1st”, “72nd”, “233rd”, “5206th”).

function ordinal($n) {
	$t = $n % 100;
	if ($t == 11 or $t == 12 or $t == 13) return $n . 'th';
	$t = $n % 10;
	if ($t == 1) return $n . 'st';
	if ($t == 2) return $n . 'nd';
	if ($t == 3) return $n . 'rd';
	return $n . 'th';
}

Roman Numerals

This function converts a number to (uppercase) Roman numerals. It handles numbers between 1 and 3,999 only. For lowercase, just use strtolower(roman($n)).

function roman($n) {
	$chars = [1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X', 9 => 'IX', 5 => 'V', 4 => 'IV', 1 => 'I'];
	foreach ($chars as $value => $char) while ($n >= $value) {
		$r .= $char;
		$n -= $value;
	}
	return $r;
}