Program to convert a given number to words | A function that prints given number in words ; Get number of digits in given number ; Base cases ; The first string is not used , it is to make array indexing simple ; The first string is not used , it is to make array indexing simple ; The first two string are not used , they are to make array indexing simple ; Used for debugging purpose only ; For single digit number ; Iterate while num is not ' \0' ; Code path for first 2 digits ; here len can be 3 or 4 ; Code path for last 2 digits ; Need to explicitly handle 10 - 19. Sum of the two digits is used as index of " two _ digits " array of strings ; Need to explicitely handle 20 ; Rest of the two digit numbers i . e . , 21 to 99 ; Driver Code
< ? php function convert_to_words ( $ num ) { $ len = strlen ( $ num ) ; if ( $ len == 0 ) { echo " empty ▁ string STRNEWLINE " ; return ; } if ( $ len > 4 ) { echo " Length ▁ more ▁ than ▁ 4 ▁ " . " is ▁ not ▁ supported STRNEWLINE " ; return ; } $ single_digits = array ( " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " ) ; $ two_digits = array ( " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " ) ; $ tens_multiple = array ( " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " ) ; $ tens_power = array ( " hundred " , " thousand " ) ; echo $ num . " : ▁ " ; if ( $ len == 1 ) { echo $ single_digits [ $ num [ 0 ] - '0' ] . " ▁ STRNEWLINE " ; return ; } $ x = 0 ; while ( $ x < strlen ( $ num ) ) { if ( $ len >= 3 ) { if ( $ num [ $ x ] - '0' != 0 ) { echo $ single_digits [ $ num [ $ x ] - '0' ] . " " ; echo $ tens_power [ $ len - 3 ] . " " ; } -- $ len ; } else { if ( $ num [ $ x ] - '0' == 1 ) { $ sum = $ num [ $ x ] - '0' + $ num [ $ x ] - '0' ; echo $ two_digits [ $ sum ] . " ▁ STRNEWLINE " ; return ; } else if ( $ num [ $ x ] - '0' == 2 && $ num [ $ x + 1 ] - '0' == 0 ) { echo " twenty STRNEWLINE " ; return ; } else { $ i = $ num [ $ x ] - '0' ; if ( $ i > 0 ) echo $ tens_multiple [ $ i ] . " ▁ " ; else echo " " ; ++ $ x ; if ( $ num [ $ x ] - '0' != 0 ) echo $ single_digits [ $ num [ $ x ] - '0' ] . " ▁ STRNEWLINE " ; } } ++ $ x ; } } convert_to_words ( "9923" ) ; convert_to_words ( "523" ) ; convert_to_words ( "89" ) ; convert_to_words ( "8" ) ; ? >