PHP Function To Turn Integer To Roman Numerals

Tuesday, April 22, 2008 - 13:37

Use the following function to change any integer into a string containing the integer value as a Roman Numeral.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function integerToRoman($integer)
{
 // Convert the integer into an integer (just to make sure)
 $integer = intval($integer);
 $result = '';
 
 // Create a lookup array that contains all of the Roman numerals.
 $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($integer/$value);
 
  // Add the same number of characters to the string
  $result .= str_repeat($roman,$matches);
 
  // Set the integer to be the remainder of the integer and the value
  $integer = $integer % $value;
 }
 
 // The Roman numeral should be built, return it
 return $result;
}

To run the code just give the function an integer. Here are some examples.

1
2
3
4
5
echo integerToRoman(1).'<br />';
echo integerToRoman(42).'<br />';
echo integerToRoman(123).'<br />';
echo integerToRoman(4576).'<br />';
echo integerToRoman(1979).'<br />';

This will print out the following.

1
2
3
4
5
I
XLII
CXXIII
MMMMDLXXVI
MCMLXXIX

You can also give the function a string.

echo integerToRoman('765').'<br />';

Will print out DCCLXV.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Nice work.....Thanks

Nice work! I asked the internet and lo, there you were.

Add new comment