
How to display numbers with Ordinal suffix like 1st, 2nd,3rd,etc ?
Ordinal numbers shows the order of elements in a set. In other words they show rank or position. “First” and “second” are both ordinal numbers but they do not say anything about the distance between first and second.
Ordinal numbers may be written in English with numerals and letter suffixes: 1st, 2nd or 2d, 3rd or 3d, 4th, 11th, 21st, 101st, 477th, etc., with the suffix acting as an ordinal indicator.
In this tutorial we’ll discuss how to display numbers with ordinal suffix like 1st, 2nd, 3rd,4th,etc.
PHP :
public function ordinal($number)
{
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if ((($number % 100) >= 11) && (($number%100) <= 13))
return $number. 'th';
else
return $number. $ends[$number % 10];
}
echo ordinal('5');
Explanation :
Above example,
- Define a function named ordinal() with a parameter $number.
- Declare suffix as an array and define to a variable.
- if $number % 100 greater than or equal to 11 and $number % 100 is less than or equal to 13 that is, $number % 100 is in between 11 and 13 it’s suffix is considered as ‘th’.
- else find the $number % 10 th index of suffix array.
For other php solutions please visit Php