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

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

Last updated: January 10, 2024

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.

Next Article: PHP: Checking if a Number is Odd or Even

Previous Article: PHP: Convert bytes to KB, MB, GB and vice versa

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array