PHP to convert numbers to words (e.g. 123 to “one hundred twenty-three”)
Code:
function convertNumberToWords($number) {
// Define an array of words for numbers 0-9
$words = array(
'',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
);
// Define an array of words for tens
$tens = array(
'',
'ten',
'twenty',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
);
// Convert the number to a string
$numberString = (string) $number;
// Get the length of the number
$length = strlen($numberString);
// If the number is less than 10, return the word for the number
if ($length == 1) {
return $words[$number];
}
// If the number is less than 20, return the word for the tens place
if ($length == 2) {
return $tens[$numberString[0]] . ' ' . $words[$numberString[1]];
}
// If the number is less than 100, return the word for the tens place followed by the word for the ones place
if ($length == 3) {
return $words[$numberString[0]] . ' hundred ' . $tens[$numberString[1]] . ' ' . $words[$numberString[2]];
}
// If the number is less than 1000, return the word for the hundreds place followed by the word for the tens place and the word for the ones place
if ($length == 4) {
return $words[$numberString[0]] . ' thousand ' . $tens[$numberString[1]] . ' ' . $words[$numberString[2]] . ' ' . $words[$numberString[3]];
}
// If the number is less than 10000, return the word for the thousands place followed by the word for the hundreds place, the word for the tens place, and the word for the ones place
if ($length == 5) {
return $words[$numberString[0]] . ' ten thousand ' . $tens[$numberString[1]] . ' ' . $words[$numberString[2]] . ' ' . $words[$numberString[3]] . ' ' . $words[$numberString[4]];
}
// If the number is greater than 10000, return an error message
return 'The number is too large to convert to words.';
}
Explanation:
This function converts a number to its corresponding word representation. It does this by first checking the length of the number and then using a series of nested if statements to determine the appropriate words to use.
For example, if the number is less than 10, the function will simply return the word for the number. If the number is less than 20, the function will return the word for the tens place followed by the word for the ones place. If the number is less than 100, the function will return the word for the hundreds place followed by the word for the tens place and the word for the ones place. And so on.
Example:
The following code converts the number 123 to its corresponding word representation:
$number = 123;
$words = convertNumberToWords($number);
echo $words;
This code will output the following:
one hundred twenty-three