PHP: Adding suffixes to numbers (e.g. 1st, 2nd, 3rd, 4th)

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Attaching the correct ordinal suffix to a number in PHP is a common task that enhances the readability of numerical lists and data. This tutorial guides you through the process using PHP.

Getting Started with Basic Suffixes

To start with, let’s consider a straightforward approach:

function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100), array(11,12,13))){
        switch ($num % 10) {
            case 1: return $num.'st';
            case 2: return $num.'nd';
            case 3: return $num.'rd';
        }
    }
    return $num.'th';
}

// Usage example:
echo addOrdinalNumberSuffix(1);  // Output: 1st
echo addOrdinalNumberSuffix(2);  // Output: 2nd
echo addOrdinalNumberSuffix(3);  // Output: 3rd
echo addOrdinalNumberSuffix(4);  // Output: 4th

The above function checks whether the number is not within the special cases (11, 12, or 13) and then determines the appropriate suffix.

Handling Edge Cases

While the basic setup works well for most numbers, we must consider all edge cases, such as large numbers and decimal values:

function addOrdinalNumberSuffix($num) {
    if (!is_numeric($num)) {
        return false; // Not a number
    }
    $num = (int)$num; // Casting floats to integers
    if ($num < 0) {
        return false; // Negative numbers are not supported
    }
    if (($num % 100 >= 11) && ($num % 100 <= 13)) {
        return $num . 'th';
    }
    switch ($num % 10) {
        // ...remain the same as above
    }
}

Localizing Suffixes

Localization is important in global applications. Let’s add support for different languages:

function addOrdinalNumberSuffix($num, $language = 'en') {
    $suffixes = array(
        'en' => array('st', 'nd', 'rd', 'th'),
        'fr' => array('er', 'e', 'e', 'e'), // Example for French
        // ... 
    );
    if (!isset($suffixes[$language])) {
        $language = 'en'; // Default to English if the language is not supported
    }
    // ... handle the same logic as above and use the $suffixes array
}

We can define suffix arrays for each language, providing local adaptation without changing the core logic.

Creating a More Dynamic Function

We can make our function more robust by accepting both numeric strings and actual numbers, as well as by adding functionality to handle negative numbers, decimals, and formatting options:

function addOrdinalNumberSuffix($num, $options = array()) {
    // ... add more configuration to the options array 
    // ... to handle decimals, negatives, and formatting
}

// Implementing further customization using the options array

Create options params and instantiate new settings based on these configurations to handle more complex scenarios.

Utilizing Libraries and Frameworks

Rather than reinventing the wheel, you can leverage existing libraries and frameworks that offer built-in functions for adding ordinal suffixes to numbers:

// Using a framework function like Laravel’s Str::ordinal()
echo Str::ordinal(1); // Output: 1st
echo Str::ordinal(2); // Output: 2nd

Always consider community-tested solutions before writing custom functions.

Conclusion

In this tutorial, we’ve explored various methods to add ordinal suffixes to numbers in PHP, considering different use cases and levels of complexity. Whether you’re building an application that uses ordinal numbers frequently, or you just need them occasionally, PHP provides the flexibility and options to handle this task elegantly.