PHP: Mapping numbers to words (e.g. 1 to ‘one’, 2 to ‘two’)

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

Introduction

Mapping numbers to their word equivalents is a common task in various programming scenarios, such as generating human-readable reports, providing linguistic context in user interfaces, or programming educational software. In PHP, this can be achieved through conditional statements or by utilizing specialized libraries. In this tutorial, we’ll explore some methods to convert numbers to words in PHP.

Using Conditional Statements

One way to convert numbers to words is to use a series of if or switch statements. This works for small ranges of numbers, but becomes impractical as the number range increases.

# Example using switch statement
switch ($number) {
    case 1:
        echo 'one';
        break;
    case 2:
        echo 'two';
        break;
    // Add cases for additional numbers
}

Creating a Function for Small Ranges

For a finite and relatively small range of numbers, you can create a custom function that maps numbers to words using an array.

function numberToWord($number) {
    $words = ['zero','one','two','three','four','five','six','seven','eight','nine','ten'];
    if ($number < 0 || $number > count($words) - 1) {
        return 'Number out of range';
    }
    return $words[$number];
}
echo numberToWord(2); // Outputs 'two'

Going Beyond Ten

If you need to map numbers beyond ten, you’ll have to build a more sophisticated function. This function will need to consider the linguistic structure of number words, such as the difference between ‘twenty’ and ‘twenty-one’.

/**
* Map an integer to its English word representation.
* Handles numbers up to 999.
*/
function numberToWord($number) {
    if (!is_numeric($number) || $number < 0 || $number > 999) {
        return 'Invalid number';
    }
    $num = intval($number);
    // Define words
    $ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    $teens = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
    $tens = ['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'];
    // Check for special cases
    if ($num < 10) {
        return $ones[$num];
    } else if ($num < 20) {
        return $teens[$num - 10];
    } else {
        // Decompose number
        $tensDivision = intdiv($num, 10);
        $remainder = $num % 10;
        $word = $tens[$tensDivision];
        if ($remainder) {
            $word .= '-' . $ones[$remainder];
        }
        return $word;
    }
}
echo numberToWord(25); // Outputs 'twenty-five'

Using a PHP Library

For a more comprehensive solution, you can make use of a PHP library like NumberFormatter (part of the intl extension), which can handle a wide range of numbers and localize the formatting.

// Make sure the intl extension is installed and enabled
$formatter = new 
umberformatter("en", 
umberformatter::SPELLOUT);
echo $formatter->format(12345); // Outputs 'twelve thousand three hundred forty-five'

Best Practices

When creating your own functions for mapping numbers to words in PHP, here are some tips to consider:

  • Validate the input to ensure that it is an integer and within the supported range.
  • Ensure that your function handles edge cases, such as zero or negative numbers, properly.
  • Use recursion for handling larger numbers to simplify the logic for hundreds, thousands, etc.
  • Test your function extensively with various inputs to ensure accuracy.

Conclusion

Mapping numbers to words in PHP is relatively straightforward for small ranges. For larger numbers, it’s recommended to use a dedicated library that handles a variety of cases and languages. This tutorial provided the basic understanding needed to implement a number-to-word conversion in PHP, from simple implementations to using robust libraries.