Ordinal numbers with PHP

Ordinal numbers with PHPEver needed to add ordinal numbers to a web page using PHP? Now you can with this very simple function. It simply looks for a pattern in the number and then returns the number, plus the correct ordinal type, using a simple if statement.

Example of ordinal numbers:

Change 1, 2, 3, 4, 5, etc
To 1st, 2nd, 3rd, 4th, 5th, etc

/// ORDINAL NUMBER TRANSLATOR
function ordinal_numbers($NUM)
{
	if(strlen($NUM)>1 && substr($NUM, -2, 1) == 1) // TEENS
	{ return "th"; }

	else // ALL OTHERS
	{
		$num = substr($NUM, -1); /// GET LAST NUMBER
		if($num == 0) { return "th"; }
		if($num == 1) { return "st"; }
		if($num == 2) { return "nd"; }
		if($num == 3) { return "rd"; }
		if($num >= 4 && $num <= 9) { return "th"; }
	}
}
///

Leave a Reply

Your email address will not be published. Required fields are marked *