Convert a Roman Numeral To a Number in PHP

Reading Time: 3 minutes
561 Views

Inside this article we will see the concept i.e Convert a Roman Numeral To a Number in PHP. Article contains the classified information i.e Roman Numeral to Integers.

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: Do you Know The Best Programming Languages for AI?

Let’s get started.

Application Programming

Create a folder with name roman-integer.

Next, create a file index.php inside it.

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

<?php 

// Function to convert a Roman numeral To Integer
function romanToInt($s) {

    $map = [
        'I' => 1,
        'V' => 5,
        'X' => 10,
        'L' => 50,
        'C' => 100,
        'D' => 500,
        'M' => 1000,
    ];

    $result = 0;
    $prev = 0;
    $len = strlen($s);

    for ($i = $len - 1; $i >= 0; $i--) {
        $curr = $map[$s[$i]];
        if ($curr >= $prev) {
            $result += $curr;
        } else {
            $result -= $curr;
        }
        $prev = $curr;
    }
    return $result;
}

// Call function
echo romanToInt('XXI');

Here, we have the complete code.

Application Testing

Open your browser.

Read More: Top Mobile App Development Programming Languages

Next,

Your project URL will be like this.

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

21

Output #2

// Call function
echo romanToInt('MCMXCIV');

This will output as,

1994

We hope this article helped you to learn about Convert a Roman Numeral To a Number 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