How to convert Number to Roman numerals in PHP
Snippet
Use the following function to convert any integer to a string containing a Roman numeral.
<?php
/**
* @param int $number
* @return string
*/
function numberToRoman(int $number) {
$map = ['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;
}
//USING
echo numberToRoman(3); // III
echo numberToRoman(114); // CXIV
If you need to convert online, you can use our free tool - Number to Roman numerals Converter.