Open In App

PHP Program to Convert Integer to Roman Number

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting an integer to a Roman number is a common problem often encountered in applications dealing with dates, historical data, and numeral representations. In this article, we will explore various approaches to converting an integer to Roman numerals in PHP.

Using Simple Mapping Array

A basic method is to use a mapping array that represents the correspondence between integer values and Roman numerals.

PHP




<?php
function intToRoman($num) {
    $mapping = [
        1000 => 'M',
        900 => 'CM',
        500 => 'D',
        400 => 'CD',
        100 => 'C',
        90 => 'XC',
        50 => 'L',
        40 => 'XL',
        10 => 'X',
        9 => 'IX',
        5 => 'V',
        4 => 'IV',
        1 => 'I'
    ];
  
    $result = '';
  
    foreach ($mapping as $value => $roman) {
        while ($num >= $value) {
            $result .= $roman;
            $num -= $value;
        }
    }
  
    return $result;
}
  
// Driver code
$num = 3549;
  
echo "Roman numeral for $num is: " 
    . intToRoman($num);
      
?>


Output

Roman numeral for 3549 is: MMMDXLIX

Using Recursive Approach

A recursive approach is also possible for converting an integer to Roman numerals.

PHP




<?php
  
function intToRoman($num) {
    if ($num <= 0) {
        return '';
    }
  
    $mapping = [
        1000 => 'M',
        900 => 'CM',
        500 => 'D',
        400 => 'CD',
        100 => 'C',
        90 => 'XC',
        50 => 'L',
        40 => 'XL',
        10 => 'X',
        9 => 'IX',
        5 => 'V',
        4 => 'IV',
        1 => 'I'
    ];
  
    foreach ($mapping as $value => $roman) {
        if ($num >= $value) {
            return $roman . intToRoman($num - $value);
        }
    }
  
    return '';
}
  
  
// Driver code
$num = 1111;
  
echo "Roman numeral for $num is: " 
    . intToRoman($num);
      
?>


Output

Roman numeral for 1111 is: MCXI


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads