How to Display Numbers with Ordinal Suffixes in PHP
When representing numbers in an ordinal context (e.g., 1st, 2nd, 3rd, etc.), it's essential to determine the appropriate suffix to append to each number. Here's a solution to this problem in PHP:
According to Wikipedia, you can use the following logic to identify the correct ordinal suffix:
$ends = array('th','st','nd','rd','th','th','th','th','th','th'); if (($number %100) >= 11 && ($number%100) <= 13) $abbreviation = $number. 'th'; else $abbreviation = $number. $ends[$number % 10];
In this code snippet, $number represents the number you wish to format.
To implement this logic as a reusable function:
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]; } //Example Usage echo ordinal(100);
The above is the detailed content of How to Add Ordinal Suffixes (1st, 2nd, 3rd, etc.) to Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!