Skip to content

Instantly share code, notes, and snippets.

@zgover
Last active April 28, 2021 10:39
Show Gist options
  • Save zgover/ac3b5d5bbf11ebe9b7e6776ba07bb6bc to your computer and use it in GitHub Desktop.
Save zgover/ac3b5d5bbf11ebe9b7e6776ba07bb6bc to your computer and use it in GitHub Desktop.
[Year to Roman] Convert 4 digit year into Roman Numeral #date #convert #helper

lang: PHP

function roman_year(int $year = null): string {
    $year = $year ?? date('Y');
    $romanNumerals = [
        '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,
    ];
    $result = '';
    foreach ($romanNumerals as $roman => $yearNumber) {
        // Divide to get  matches
        $matches = intval($year / $yearNumber);
        // Assign the roman char * $matches
        $result .= str_repeat($roman, $matches);
        // Substract from the number
        $year = $year % $yearNumber;
    }
    return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment