Home >Backend Development >PHP Tutorial >How Can I Add Ordinal Suffixes (st, nd, rd, th) to Numbers in PHP?
Displaying Numbers with Ordinal Suffixes in PHP
In various contexts, it is necessary to display numbers with their corresponding ordinal suffixes (st, nd, rd, th). This article explores a PHP-based approach to achieve this transformation.
The essence of the solution lies in identifying the correct ordinal suffix based on the last digit of the number. An array of ordinal suffixes can be defined:
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
For numbers between 11 and 13, the suffix "th" is used universally. For other numbers, the corresponding suffix is selected from the array based on the last digit of the number:
if (($number %100) >= 11 && ($number%100) <= 13) $abbreviation = $number. 'th'; else $abbreviation = $number. $ends[$number % 10];
As an example, for the number 100, the corresponding ordinal suffix would be "th". Similarly, for the number 22, the ordinal suffix would be "nd".
This approach can be encapsulated within a function for easy use:
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]; }
This function can be invoked with a number as an argument and returns the corresponding number with the ordinal suffix. For instance, ordinal(100) would return "100th".
The above is the detailed content of How Can I Add Ordinal Suffixes (st, nd, rd, th) to Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!