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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-27 00:26:10756browse

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

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 &amp;&amp; ($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) &amp;&amp; (($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!

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