PHP Add Ordinal Number format 1st 2nd 3rd 4th 11th 12th 21st

4.18K views
no comments
4 Apr 2016 1:21 am

I was working on my site featuring posts for dynamic data which I can get from csv and show listing in Ordinal number format then I think it should be a define function to dynamically set ordinal number format. Here is function I have defined and posted here.

In function used first parameter for number only and second parameter is used to add sup html tag which can automatically move Ordinal format to top position both are examples defined in below.

This function is mostly used to show months dates with Ordinal format eg: today is 29th February 2016

function OrdinalNumberFormat($number,$add_sup=false){
	$format = 'th';
	$numlen = strlen($number);
	$lasttwonum = substr($number,$numlen-2,2);
	$lastone = substr($number,$numlen-1,1);
	if( ($lastone==1 || $number==1 ) && $lasttwonum!=11){
		$format = 'st';
	} else if($lastone==2 && $lasttwonum!=12){
		$format = 'nd';
	} else if($lastone==3 && $lasttwonum!=13){
		$format = 'rd';
	}
	if($add_sup===true){
		$format = '<sup>'.$format.'</sup>';
	}
	return $number.$format;
}

Ordinal Number Format example without sup tag

for($OrdinalINC=1; $OrdinalINC<=50;$OrdinalINC++){
	echo OrdinalNumberFormat($OrdinalINC).' ';
}

1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 31st 32nd 33rd 34th 35th 36th 37th 38th 39th 40th 41st 42nd 43rd 44th 45th 46th 47th 48th 49th 50th

Ordinal Number Format example sup tag

for($OrdinalINC=51; $OrdinalINC<=100;$OrdinalINC++){
	echo OrdinalNumberFormat($OrdinalINC,true).' ';
}

51st 52nd 53rd 54th 55th 56th 57th 58th 59th 60th 61st 62nd 63rd 64th 65th 66th 67th 68th 69th 70th 71st 72nd 73rd 74th 75th 76th 77th 78th 79th 80th 81st 82nd 83rd 84th 85th 86th 87th 88th 89th 90th 91st 92nd 93rd 94th 95th 96th 97th 98th 99th 100th

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>