How to use a Pre-defined Array of Words In PHP
In this method we use pre-defined arrays containing words for units, tens, and special cases like numbers 11-19. It processes the given number by breaking it down into its individual digits and constructs the word representation by concatenating the corresponding words from the arrays.
Example: Below is the implementation of the above approach to convert a given number to words.
<?php
function numToWords($number) {
$units = array('', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine');
$tens = array('', 'ten', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty',
'ninety');
$special = array('eleven', 'twelve', 'thirteen',
'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen');
$words = '';
if ($number < 10) {
$words .= $units[$number];
} elseif ($number < 20) {
$words .= $special[$number - 11];
} else {
$words .= $tens[(int)($number / 10)] . ' '
. $units[$number % 10];
}
return $words;
}
// Example usage:
$number = 90;
echo "Number $number in words: "
. numToWords($number);
?>
Output
Number 90 in words: ninety
Time Complexity: O(Log10(N))
Auxiliary Space: O(1)
PHP Program to Convert a Given Number to Words
Given an integer N, the task is to convert the given number into words using PHP.
Examples:
Input: N = 438237764
Output: Four Hundred Thirty Eight Million Two Hundred Thirty Seven Thousand Seven Hundred Sixty Four
Input: N = 1000
Output: One Thousand
Below are the approaches to convert a given number to words:
Table of Content
- Using a Pre-defined Array of Words
- Using Recursive Function for Large Numbers