Wednesday 23 January 2019

PHP Number to Romans Numeral conversion

Just Playing with PHP lately and thought of a Digit to Roman Numerals conversion. This is one of my testing exam before and just recall how I did it.



$romanString = '';
$value = 975;
 do {
   $converted = convertToRoman($value); 
   $value = $converted[0];
   $romanString = $romanString .  $converted[1];
 } while ( $value != 0);

echo $romanString;

 function convertToRoman($number){
    $returnValue = 0;
    $returnString = '';
 $romanArray = [[1000,'M'],[900,'CM'],[100,'C'],[90,'XC'],[50,'L'],[10,'X'],[9,'IX'],[5,'V'],[4,'IV'],[1,'I']];

 foreach ($romanArray as  $value) {
  
       if ($number >= $value[0]) {
            $returnValue = $number - $value[0];
            $returnString = $value[1]; 
            break;
       }        

 }
     
 return array($returnValue,$returnString);
}

Share:

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.