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.

<?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>
Leave A Reply

Your email address will not be published.

2 Comments
  1. Vara Prasad says

    i have small doubt in php that is how can i update student year like 1, 2, 3,4. it will update automatically when complete one year and add 3000 rs amount in their balance box.

  2. Vara Prasad says

    i have small doubt in php that is how can i update student year like 1, 2, 3,4. it will update automatically when complete one year and add 3000 rs amount in their balance box.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Privacy & Cookies Policy