PHP Function To Turn Integer To Roman Numerals

22nd April 2008 - 2 minutes read time

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

  1. function integerToRoman($integer)
  2. {
  3. // Convert the integer into an integer (just to make sure)
  4. $integer = intval($integer);
  5. $result = '';
  6.  
  7. // Create a lookup array that contains all of the Roman numerals.
  8. $lookup = array('M' => 1000,
  9. 'CM' => 900,
  10. 'D' => 500,
  11. 'CD' => 400,
  12. 'C' => 100,
  13. 'XC' => 90,
  14. 'L' => 50,
  15. 'XL' => 40,
  16. 'X' => 10,
  17. 'IX' => 9,
  18. 'V' => 5,
  19. 'IV' => 4,
  20. 'I' => 1);
  21.  
  22. foreach($lookup as $roman => $value){
  23. // Determine the number of matches
  24. $matches = intval($integer/$value);
  25.  
  26. // Add the same number of characters to the string
  27. $result .= str_repeat($roman,$matches);
  28.  
  29. // Set the integer to be the remainder of the integer and the value
  30. $integer = $integer % $value;
  31. }
  32.  
  33. // The Roman numeral should be built, return it
  34. return $result;
  35. }

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

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

This will print out the following.

  1. I
  2. XLII
  3. CXXIII
  4. MMMMDLXXVI
  5. MCMLXXIX

You can also give the function a string.

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

Will print out DCCLXV.

Comments

Permalink
Nice work.....Thanks

Aminu Abdulsalami (Sun, 03/17/2013 - 10:56)

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

Chris Pink (Tue, 12/12/2017 - 13:37)

Permalink

Hey thanks for this man!

Marc Crosthwaite (Sun, 09/01/2019 - 16:15)

Add new comment

The content of this field is kept private and will not be shown publicly.