How to use Simple Mapping Array In PHP
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
PHP Program to Convert Integer to Roman Number
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.
Table of Content
- Using Simple Mapping Array
- Using Recursive Approach