How to convert number to String in PHP
In this method, to convert an integer to string, write (string) before the integer, and PHP will convert it to string type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?php error_reporting(0); function convertNumberToWord($num = false) { $num = str_replace(array(',', ' '), '' , trim($num)); if(! $num) { return false; } $num = (int) $num; $words = array(); $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ); $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred'); $list3 = array('', 'thousand', 'million', 'billion' ); $num_length = strlen($num); $levels = (int) (($num_length + 2) / 3); $max_length = $levels * 3; $num = substr('00' . $num, -$max_length); $num_levels = str_split($num, 3); for ($i = 0; $i < count($num_levels); $i++) { $levels--; $hundreds = (int) ($num_levels[$i] / 100); $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ( $hundreds == 1 ? '' : 's' ) . ' ' : ''); $tens = (int) ($num_levels[$i] % 100); $singles = ''; if ( $tens < 20 ) { $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' ); } else { $tens = (int)($tens / 10); $tens = ' ' . $list2[$tens] . ' '; $singles = (int) ($num_levels[$i] % 10); $singles = ' ' . $list1[$singles] . ' '; } $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' ); } $commas = count($words); if ($commas > 1) { $commas = $commas - 1; } $data= implode(' ', $words); return $data." ".'only'; } if(isset($_POST['confirm'])){ echo "<p style=color:red>".convertNumberToWord($_POST['number'])."</p><br>"; } ?> <form method="post"> Enter Number: <input type="" name="number" value='' required /></br></br> <input type="submit" name="confirm" value='Convert Into String' /> </form> |