Roman numerals are a numeric system originating from ancient Rome, using specific letters to represent numbers. Common Roman numerals include I (1), V (5), X (10), L (50), C (100), D (500), and M (1000). Numbers are formed by combining these characters. For example, XIX represents 19, meaning 'ten plus nine'.
In PHP, converting an integer to a Roman numeral can be done with a straightforward function. This method uses an array to map numbers to Roman characters and employs loops and string functions to build the result. Here is the complete function code:
function integerToRoman($integer)
{
$integer = intval($integer);
$result = '';
$romanNumerals = 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 ($romanNumerals as $roman => $value) {
$matches = intval($integer / $value);
$result .= str_repeat($roman, $matches);
$integer = $integer % $value;
}
return $result;
}
This function converts the input to an integer, initializes an empty string for the result, and defines an array mapping Arabic numbers to Roman numerals. It loops through the array, repeatedly adding the appropriate Roman numeral character until the entire number is converted.
Here are several examples demonstrating how to use the function to convert integers to Roman numerals and output the results:
echo integerToRoman(1) . "\n"; // I
echo integerToRoman(4) . "\n"; // IV
echo integerToRoman(9) . "\n"; // IX
echo integerToRoman(50) . "\n"; // L
echo integerToRoman(100) . "\n"; // C
echo integerToRoman(500) . "\n"; // D
echo integerToRoman(1000) . "\n"; // M
Running the above code outputs:
I
IV
IX
L
C
D
M
This article demonstrates a simple yet effective approach to convert integers to Roman numerals in PHP by using array mapping and string operations. The method is easy to understand, efficient, and suitable both for practical use and as a programming exercise.