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

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

DDD
Release: 2024-11-25 17:21:14
Original
327 people have browsed it

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

Displaying Numbers with Ordinal Suffixes in PHP

When displaying numbers in certain contexts, it is necessary to append the appropriate ordinal suffix (st, nd, rd, or th) to indicate their order. This can be challenging, especially for large or complex numbers.

Finding the Correct Suffix

To determine the correct ordinal suffix for a number, one can utilize an array-based approach. This involves storing the suffixes in an array and selecting the appropriate one based on the last digit of the number.

Code Implementation

The following PHP code snippet demonstrates how to implement the ordinal suffix array method:

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

In this code, the $ends array contains the ordinal suffixes from 0th to 9th. The logic checks whether the number's last two digits are between 11 and 13, in which case it assigns 'th' as the suffix. Otherwise, it selects the suffix based on the last digit using the modulo operator (%).

Function-Based Approach

Alternatively, you can create a function to simplify the ordinal suffix calculation:

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

// Example usage:
echo ordinal(100);
Copy after login

Conclusion

By utilizing the array-based or function-based approach, you can effortlessly display numbers with the correct ordinal suffixes, ensuring clarity and accuracy in your code.

The above is the detailed content of How to Efficiently 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template