Roman numerals are a great way to add a bit of class to a web page. They are often used in official titles, such as the XXXIV Pennsic War (34th). The rules for Roman numerals are straightforward and therefore lend themselves to being scripted. The basic rules of Roman numerals are:
M = 1,000 C = 100 X = 10 I = 1 D = 500 L = 50 V = 5
It should be noted that although other prefix combinations could theoretically be possible (such as IC to equal 99), these are not normally used and therefore can be ignored. A function to return the Roman numeral representation of a number is given in Listing A.
We could have used a brute force technique to accomplish this, handling each case one at a time; however, a more elegant solution presents itself. Instead an array is created and filled with all the possible legal combinations in order. Starting with the highest value possible, and working our way down, we see how many times that value will go evenly into the number.
We then insert the value that many times. Next we subtract the value just created from the number and loop again. Of course, some cases such as "IV" should only appear once, but by the virtue of this algorithm, that is the case. If, for example, a number ended in 8, it would first be divided by 5, producing "V", and then reduced to 3, which would produce "III", creating the correct notation. The special cases will never get the chance to be printed multiple times.
// A function to return the Roman Numeral, given an integer
// Make sure that we only use the integer portion of the value
$n = intval($num);
$result = '';
// Declare a lookup array that we will use to traverse the number:
$lookup = 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);
foreach ($lookup as $roman => $value)
// Determine the number of matches
$matches = intval($n / $value);
// Store that many characters
$result .= str_repeat($roman, $matches);
// Substract that from the number
$n = $n % $value;
// The Roman numeral should be built, return it
// Outputs MMVII