Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

PHP: Convert a Roman numeral to a Number

Use the following function to convert/change a given Roman numeral to an integer/number.

function romanToInt($s) {
    $romanToNumberMap = [
        'I' => 1,
        'V' => 5,
        'X' => 10,
        'L' => 50,
        'C' => 100,
        'D' => 500,
        'M' => 1000,
    ];
   $romanChars = array_map("strrev", array_reverse(str_split(strrev($s), 2)));
   $output = 0;
   foreach($romanChars as $romanChar) {
    $previousNumericValue = 1;
    $currentNumericValue= 0;
    for($i=0, $c=strlen($romanChar); $i < $c; $i++) { 
       $n = $romanToNumberMap[$romanChar[$i]];
       $currentNumericValue = abs($previousNumericValue < $n ? $currentNumericValue -=$n : $currentNumericValue +=$n);
       $previousNumericValue = $n;
    }
    $output += $currentNumericValue;
   }
    
    return $output;
}

var_dump(romanToInt('III')); // int(3)
var_dump(romanToInt('LVIII')); // int(58)
var_dump(romanToInt('MCMXCIV')); // int(1994)
var_dump(romanToInt('IV')); // int(4)

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments