Home > Backend Development > PHP Tutorial > How Can I Add Ordinal Suffixes (st, nd, rd, th) to Numbers in PHP?

How Can I Add Ordinal Suffixes (st, nd, rd, th) to Numbers in PHP?

Barbara Streisand
Release: 2024-11-27 02:12:14
Original
942 people have browsed it

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

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

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

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!

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