Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function number2words(int $number): string
{
if ($number < 20) {
return ones2words($number);
} elseif ($number < 100) {
return tens2words($number);
} elseif ($number < 1000) {
return hundreds2words($number);
} elseif ($number < 1000000) {
return thousands2words($number);
}
throw new OutOfRangeException();
}
function ones2words(int $number): string
{
$ones = [
0 => 'zero',
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five",
6 => "six",
7 => "seven",
8 => "eight",
9 => "nine",
10 => "ten",
11 => "eleven",
12 => "twelve",
13 => "thirteen",
14 => "fourteen",
15 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen"
];
return $ones[$number] ?? '';
}
function tens2words(int $number): string
{
$tens = [
1 => "ten",
2 => "twenty",
3 => "thirty",
4 => "forty",
5 => "fifty",
6 => "sixty",
7 => "seventy",
8 => "eighty",
9 => "ninety"
];
return implode('-', array_filter([
$tens[floor($number / 10)] ?? '',
ones2words($number % 10 ?: -1),
]));
}
function hundreds2words(int $number): string
{
return implode(' ', array_filter([
ones2words(floor($number / 100)),
'hundred',
number2words($number % 100 ?: -1),
]));
}
function thousands2words(int $number): string
{
return implode(' ', array_filter([
number2words(floor($number / 1000)),
'thousand',
number2words(floor($number % 1000) ?: -1),
]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment