Skip to content

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)
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments