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
Release: 2024-11-27 00:26:10
Original
727 people have browsed it

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];
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template