24 July 2018

Helper function for converting numbers to words. There is same function available in PHPs NumberFormatter class, but using it is not always possible, since it's not enabled by default.

Source code viewer
  1. /**
  2.   * Helper function for converting numbers to words.
  3.   *
  4.   * @param int $num
  5.   * Integer that is going to be converted to words.
  6.   *
  7.   * @return string
  8.   * Return the number in words.
  9.   */
  10. function NumberToWord($num) {
  11. $words = array();
  12. $list1 = array(
  13. '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
  14. 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
  15. 'seventeen', 'eighteen', 'nineteen',
  16. );
  17. $list2 = array(
  18. '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
  19. 'eighty', 'ninety', 'hundred',
  20. );
  21. $list3 = array(
  22. '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
  23. 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion',
  24. 'decillion', 'undecillion', 'duodecillion', 'tredecillion',
  25. 'quattuordecillion', 'quindecillion', 'sexdecillion', 'septendecillion',
  26. 'octodecillion', 'novemdecillion', 'vigintillion',
  27. );
  28. $num_length = strlen($num);
  29. $levels = (int) (($num_length + 2) / 3);
  30. $max_length = $levels * 3;
  31. $num = substr('00' . $num, - $max_length);
  32. $num_levels = str_split($num, 3);
  33. for ($i = 0; $i < count($num_levels); ++$i) {
  34. $levels--;
  35. $hundreds = (int) ($num_levels[$i] / 100);
  36. $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ' ' : '');
  37. $tens = (int) ($num_levels[$i] % 100);
  38. $singles = '';
  39. if ($tens < 20) {
  40. $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
  41. }
  42. else {
  43. $tens = (int) ($tens / 10);
  44. $tens = ' ' . $list2[$tens] . ' ';
  45. $singles = (int) ($num_levels[$i] % 10);
  46. $singles = ' ' . $list1[$singles] . ' ';
  47. }
  48. $words[] = $hundreds . $tens . $singles . (($levels && (int) $num_levels[$i]) ? ' ' . $list3[$levels] . ' ' : '');
  49. }
  50.  
  51. return implode(' ', $words);
  52. }
Programming Language: PHP