Home  >  Article  >  Backend Development  >  How Can I Add Ordinal Suffixes (1st, 2nd, 3rd, etc.) to Numbers in PHP?

How Can I Add Ordinal Suffixes (1st, 2nd, 3rd, etc.) to Numbers in PHP?

DDD
DDDOriginal
2024-11-27 03:34:09954browse

How Can I Add Ordinal Suffixes (1st, 2nd, 3rd, etc.) to Numbers in PHP?

Displaying Numbers with Ordinal Suffixes in PHP

Numerous situations may necessitate the display of numbers with their corresponding ordinal suffixes, such as "1st," "2nd," etc. To accomplish this in PHP, a systematic approach is required.

The solution involves utilizing an array to store the ordinal suffixes, which are typically 'th,' 'st,' 'nd,' and 'rd.' Based on the number's value, the appropriate suffix can be retrieved from the array.

When the number's unit digit is anything other than 1, 2, or 3, the suffix 'th' is appended. However, if the unit digit is 1, the suffix 'st' is used; 'nd' is used if the unit digit is 2; and 'rd' is used if the unit digit is 3.

The following code snippet provides a practical example:

$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];
}

This approach ensures the correct ordinal suffix is appended to each number, regardless of its value.

The above is the detailed content of How Can I Add Ordinal Suffixes (1st, 2nd, 3rd, etc.) to Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn