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
Simply add up the letters to equal the number you want. Always list the higher numbers
first.The only exception to this rule is that you can place any lower letter in front of a
higher letter to mean minus—for example, IV = 4, IX = 9, XL = 40, XC = 90, CD =
400, and CM = 900.
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.
<?php
// A function to return the Roman Numeral, given an integer
function romanize($num) {
// 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);
// Now, let's work our way through the values, building the string
// as we go: At each step, divide out the maximum matches at this
// level, echo out that many characters and then drop the number
// down to the remainder and repeat:
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
return $result;
}
// Convert various numbers to Roman Numerals and echo them. Should display:
// 2005 = MMV
// 1999 = MCMXCIX
// 42 = XLII
echo '<pre>';
echo "\n 2005 = ", romanize(2005);
echo "\n 1999 = ", romanize(1999);
echo "\n 42 = ", romanize(42);
echo '</pre>';
?>
Popularity: 30% [?]