Skip to content

Instantly share code, notes, and snippets.

@fatkulnurk
Last active March 10, 2022 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fatkulnurk/fcd5be7e3ceedb9c15211d251a046dbe to your computer and use it in GitHub Desktop.
Save fatkulnurk/fcd5be7e3ceedb9c15211d251a046dbe to your computer and use it in GitHub Desktop.
php convert number to roman and roman to number

**Number To Roman""

Source from: https://stackoverflow.com/questions/14994941/numbers-to-roman-numbers-with-php

/**
 * @param int $number
 * @return string
 */
function numberToRomanRepresentation($number) {
    $map = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
    $returnValue = '';
    while ($number > 0) {
        foreach ($map as $roman => $int) {
            if($number >= $int) {
                $number -= $int;
                $returnValue .= $roman;
                break;
            }
        }
    }
    return $returnValue;
}

Roman to Number

Source: https://stackoverflow.com/questions/6265596/how-to-convert-a-roman-numeral-to-integer-in-php

$romans = array(
    'M' => 1000,
    'CM' => 900,
    'D' => 500,
    'CD' => 400,
    'C' => 100,
    'XC' => 90,
    'L' => 50,
    'XL' => 40,
    'X' => 10,
    'IX' => 9,
    'V' => 5,
    'IV' => 4,
    'I' => 1,
);

$roman = 'MMMCMXCIX';
$result = 0;

foreach ($romans as $key => $value) {
    while (strpos($roman, $key) === 0) {
        $result += $value;
        $roman = substr($roman, strlen($key));
    }
}
echo $result;
@wandersonwhcr
Copy link

wandersonwhcr commented Mar 10, 2022

if you need to convert AND validate: https://github.com/wandersonwhcr/romans

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment