class conversion number to word

#1

Dear All PHP Master,
Kindly need your help, I’m new in PHP and OOP in PHP. please help to check I have class to convert number to words below, but when I’m running it the found error message :
Notice: Undefined variable: str in C:\xampp\htdocs\latihan\oop.php on line 16
Notice: Undefined variable: str in C:\xampp\htdocs\latihan\oop.php on line 14
Notice: Undefined variable: str in C:\xampp\htdocs\latihan\oop.php on line 16
seratus dua puluh tiga juta empat ratus lima puluh enam ribu tujuh ratus delapan puluh sembilan

here it’s my code to convert number to words :

<?php Class Terbilang { Public function terbilang() { $this->dasar = array(1=>'satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan'); $this->angka = array(1000000000000,1000000000,1000000,1000,100,10,1); $this->satuan = array('triliun','milyar','juta','ribu','ratus','puluh',''); } Public function eja($n) { $i=0; while($n!=0){ $count = (int)($n/$this->angka[$i]); if($count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." "; else if($count > 0 && $count < 10) $str .= $this->dasar[$count] . " ".$this->satuan[$i]." "; $n -= $this->angka[$i] * $count; $i++; } $str = preg_replace("/satu puluh (\w+)/i","\\1 belas",$str); $str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se\\1",$str); return $str; } } $bilangan = new Terbilang; echo $bilangan -> eja(123456789); //shouldbe show :seratus dua puluh tiga juta empat ratus lima puluh enam ribu tujuh ratus delapan puluh sembilan ?>
#2

In your loop you are assigning values to the already existing $str variable using the .
[php]$str .= $this->dasar[$count] . " “.$this->satuan[$i].” ";[/php]
However, the $str variable doesn’t exist prior to this so on first run PHP will complain the variable doesn’t exist but on the second pass it does exist.

To fix, right before the while loop you should initialise the $str variable like so…

[php]$str = false;
while($n!=0){[/php]

Try that an let me know how you get on
Red :wink:

PS: Next time you post up some code, wrap it in the php code block in the editor, make it easier to read for us. :wink:

#3

Dear Redscouse,

I’m sorry for my bad English and my bad in the editor.
Many thanks for your help and now the class running well.
Great job and God bless you.

Best Regard’s
eko

#4

You’re very welcome, happy to help :wink: