Php - return count() in words

家住魔仙堡 提交于 2019-12-06 03:51:30

If it's only a handful of number:

$number = count($yournameit);
$count_words = array( "zero", "one" , "two", "three", "four" );
echo $count_words[$number];

Pear has a packge for number words. Check this out pear Number_word

$numbers = new Number_Words();
echo $number->toWords(200);

It will help you

EDIT

You can use NumberFormatter class in php.

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);  
echo $f->format(200);

It will output "Two Hundred"

If you only need to retrieve 5 numbers, the current approach is fine. Create an associative array containing the numbers as keys and corresponding word as values:

$numberArray  = array(
    0  => 'zero',
    1  => 'one',
    2  => 'two',
    3  => 'three',
    4  => 'four',
    5  => 'five',
    6  => 'six',
    // ...
);

Now, to retrieve the word corresponding to $my_count:

$my_count = 2;
echo $numberArray[$my_count]; // => two

You could optionally check if the index is defined using isset() before trying to echo it. This approach will work for numbers upto 10. However, this obviously won't work for larger numbers as it requires more complex rules. It isn't easy to create a function that does this in 10 or 20 lines of code. I suggest you use an existing solution instead of trying to create one from scratch. Take a look at the Number_Words PEAR class.

Theres no quick and easy way to achieve this with an inbuilt php function, however you can do it with this pear package: http://pear.php.net/package/Numbers_Words

The PEAR Numbers_Words package provides methods for spelling numerals in words.

Reference:

PEAR: http://pear.php.net/package/Numbers_Words

PECL: http://php.net/manual/en/numberformatter.format.php

Example:

echo number_to_word( '2281941596' );

//Sample output - number_to_word
Two Billion, Two Hundreds Eighty One Million, Nine Hundreds Forty One Thousand and Five Hundreds Ninety Six

//Sample output - PEAR Class
 two billion two hundred eighty-one million nine hundred forty-one thousand five hundred ninety-six
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!