Convert Numeric value into String in PHP


<?php
$obj = new NumberToString();
$z = array();
for ($i = 0; $i<=1000; $i++)
{
$z[] = $obj->ConvertNumber($i);
}

print_r($z);

class NumberToString
{
private static $arrNumber;

private static function GenerateArray()
{
$arr[‘0’] = “Zero”;
$arr[‘1’] = “One”;
$arr[‘2’] = “Two”;
$arr[‘3’] = “Three”;
$arr[‘4’] = “Four”;
$arr[‘5’] = “Five”;
$arr[‘6’] = “Six”;
$arr[‘7’] = “Seven”;
$arr[‘8’] = “Eight”;
$arr[‘9′] = “Nine”;
$arr[’10’] = “Ten”;
$arr[’11’] = “Eleven”;
$arr[’12’] = “Twelve”;
$arr[’13’] = “Thirteen”;
$arr[’14’] = “Fourteen”;
$arr[’15’] = “Fifteen”;
$arr[’16’] = “Sixteen”;
$arr[’17’] = “Seventeen”;
$arr[’18’] = “Eighteen”;
$arr[’19’] = “Nineteen”;
$arr[’20’] = “Twenty”;
$arr[’30’] = “Thirty”;
$arr[’40’] = “Fourty”;
$arr[’50’] = “Fifty”;
$arr[’60’] = “Sixty”;
$arr[’70’] = “Seventy”;
$arr[’80’] = “Eighty”;
$arr[’90’] = “Ninety”;
$arr[‘100’] = “Hundread”;
$arr[‘1000′] = “Thousands”;
self::$arrNumber = $arr;
}

public function ConvertNumber($Num)
{
$tmp = “”;
self::GenerateArray();
if ($Num >=0 && $Num <=20)
{
$tmp = self::$arrNumber[$Num];
}
else if (($Num == 10) || ($Num == 20) || ($Num == 30)
|| ($Num == 40) || ($Num == 50) || ($Num == 60)
|| ($Num == 70) || ($Num == 80) || ($Num == 90) || ($Num == 100) || ($Num == 1000))
{
$tmp = self::$arrNumber[$Num];
}
else if ($Num >=21 && $Num <=99)
{
$a = substr($Num,0,1) . “0”;
$b = substr($Num,1,1);
$tmp = self::$arrNumber[$a];
$tmp .= ” ” . self::$arrNumber[$b];
}
else if ($Num >=101 && $Num <=999)
{
if ($Num >=101 && $Num <=109)
{
$a = substr($Num,0,1);
$b = substr($Num,1,1);
$c = substr($Num,2,1);
$tmp = self::$arrNumber[$a];
$tmp .= self::$arrNumber[100];
if ($b != 0)
$tmp .= self::$arrNumber[$b];
$tmp .= self::$arrNumber[$c];
}
else if ($Num >=110 && $Num <=120)
{
$a = substr($Num,0,1);
$b = substr($Num,1,2);
$tmp = ” ” . self::$arrNumber[$a];
$tmp .= ” ” . self::$arrNumber[100];
$tmp .= ” ” . self::$arrNumber[$b];
}
else
{
$a = substr($Num,0,1);
$b = substr($Num,1,1) . “0”;
$c = substr($Num,2,1);
$tmp = ” ” . self::$arrNumber[$a];
$tmp .= ” ” . self::$arrNumber[100];

if ($b != ’00’)
$tmp .= ” ” . self::$arrNumber[$b];

if ($c != 0)
$tmp .= ” ” . self::$arrNumber[$c];

}
}
return “$Num = $tmp”;
}
}

?>

Tagged:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: