SnippetsProject Code

Add (th, st, nd, rd, th) to the end of a number

Description

This simple and easy function will take a number and add "th, st, nd, rd, th" after it. Example 10 to 10th.

Parameters

cdnl
An integer.

Function

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function ordinal($cdnl){
	$test_c abs($cdnl) % 10;
	$ext = ((abs($cdnl) %100 21 && abs($cdnl) %100 4) ? 'th'
			: (($test_c 4) ? ($test_c 3) ? ($test_c 2) ? ($test_c 1)
			? 'th' 'st' 'nd' 'rd' 'th'));
	return $cdnl.$ext;
} 
for($i=1;$i<100;$i++){
	echo ordinal($i).'<br>';
}
?>

Comments

ADD YOUR COMMENT:

Formatting

Comments.
Dan April 23rd
Here is mine, it doesn't give 11st, 12nd and 13rd like most do.

[code]
function make_ranked( $rank )
{
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );

if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';

if( $last == 1 && $seclast == 1) $ext = 'th'; # Avoid 11st
if( $last == 2 && $seclast == 1) $ext = 'th'; # Avoid 12nd
if( $last == 3 && $seclast == 1) $ext = 'th'; # Avoid 13rd

return $rank . $ext;

}[/code]

Not sure if these comments have code formating so may be a little messy, but works :)
mkei85 November 30th 2009
Simple one:

function ordinal($num)
{
$last=substr($num,-1);
if($last>3 or $last==0) $ext='th';
else if($last==3) $ext='rd';
else if($last==2) $ext='nd';
else $ext='st';
return $num.$ext;
}

Login



Did you want to add your own codes?
Create an Account its fast and easy!

Did you forget your username/password?
Have us reset it it for you!

Information

3.28 / 5 (392 votes)

10,342 views

2 downloads New

Code Tools

Bookmark and Share

Programmer

admin

Posted on: Jan 01, 2008

View all of Ryan's snips