Skip to content

Instantly share code, notes, and snippets.

@axeloz
Last active June 25, 2022 14:17
Show Gist options
  • Save axeloz/5d4f556d46d1ce7725ba8462ed09f6c5 to your computer and use it in GitHub Desktop.
Save axeloz/5d4f556d46d1ce7725ba8462ed09f6c5 to your computer and use it in GitHub Desktop.
Simple PHP function to convert Roman numbers to Arabic numbers
<?php
/**
* ROMAN TO ARABIC NUMBERS
* @author Axel @mabox.eu
* @param string $input
* @return int
*/
function romanToArabic(String $input):int {
$matrix = [
'M' => 1000,
'D' => 500,
'C' => 100,
'L' => 50,
'X' => 10,
'V' => 5,
'I' => 1
];
$values = [];
// First we explode the string as array
$input = str_split($input);
// Then we set the corresponding values
foreach ($input as $i) {
if (empty($matrix[$i])) {
throw new Exception('This is NOT a valid roman string');
}
array_push($values, $matrix[$i]);
}
// Finally running function to detect the sign
$pos = 0;
array_walk($values, function(&$val, $key, &$pos) use($values) {
$pos ++;
// Looping through the input, starting at next position
for ($j = $pos; $j < count($values); $j ++) {
// If the current value is lower than any following value, then we have to substract
if ($val < $values[$j]) {
$val = -$val;
break;
}
// Else nothing happens, this remains positive
}
}, $pos);
return array_sum($values);
}
// Give it a try
echo romanToArabic('MMMCDLXIV');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment