Playing with Roman numerals

The following code returns the longest Roman numeral string generated for the year between 1 and 2099. Note that the largest number that can be represented in Roman notation is 3,999 (MMMCMXCIX).



function integerToRoman($year)
{
    /* Ref: https://www.rapidtables.com/convert/number/how-number-to-roman-numerals.html 
     *      https://en.wikipedia.org/wiki/Roman_numerals
     */
    
    
    $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($year / $value);

        // Add the same number of characters to the string as the count of $matches
        $result .= str_repeat($roman,$matches);

        // Set the $year to be the remainder of the $year and the value
        $year = $year % $value;
    }
 
    return $result;
}

$longest = '';
$year = '';

for($i=1; $i <= 2099; $i++) {
    $roman = integerToRoman($i);
    if(strlen($roman) > strlen($longest)) {
        $longest = $roman;
        $year = $i;
    }
}

echo $longest . " : " . $year;

//
// MDCCCLXXXVIII : 1888
//

That will be year 1888, represented by the Roman string ‘MDCCCLXXXVIII’, which is 13 characters long. The next longest Roman number is 2888 represented by ‘MMDCCCLXXXVIII’ which has has 14 characters.