How To Convert a Integer To Roman Numeral in PHP

Reading Time: 3 minutes
533 Views

Inside this article we will see the concept i.e How To Convert a Integer To Roman Numeral in PHP. Article contains the classified information i.e PHP Function which convert a Integer To Roman Numeral.

A Roman numeral is a numeral system used in ancient Rome to represent numbers. Roman numerals use symbols such as I, V, X, L, C, D, and M to represent different values. The value of a symbol is determined by its position relative to other symbols and by the additive combination of the symbols. For example, the symbol “V” represents the value 5, and “X” represents the value 10.

Examples (Roman Numeral)

LVIII (58)
MCMXCIV (1994)
IV (4)

Read More: Convert a Roman Numeral To a Number in PHP

Let’s get started.

Application Programming

Create a folder with name integer-roman.

Next, create a file index.php inside it.

Open index.php and write this complete code into it.

<?php 

// Function to convert a Integer To Roman Number
function intToRoman($num) {
    $map = [
        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 = '';
    while ($num > 0) {
        foreach ($map as $key => $value) {
            if ($num >= $key) {
                $num -= $key;
                $result .= $value;
                break;
            }
        }
    }
    return $result;
}


// Call function
echo intToRoman(21);

You can use this function by passing in an integer, and it will return the equivalent Roman numeral.

Application Testing

Open your browser.

Read More: Do you Know The Best Programming Languages for AI?

Next,

Your project URL will be like this.

URL: http://localhost/integer-roman/index.php

XXI

Output #2

// Call function
echo intToRoman(1994);

This program will give output as,

MCMXCIV

We hope this article helped you to learn about How To Convert a Integer To Roman Numeral in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more