85. PHP Program to convert given Integer into Roman Letter.
How does this program work?
- This program is used to convert given Integer into Roman Letter using PHP.
Here is the code
<html>
<head>
<title>PHP Program To convert given Number into Roman letter</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="num" value="" placeholder="Enter a number"/> </td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<?php
function numberToRoman($num)
{
//to convert the given parameter into an integer
$n = intval($num);
$result = ' ';
// Declare an array that we will use to traverse the number
$roman_values = array(
'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 );
foreach ($roman_values as $roman => $value)
{
// Look for number of matches
$matches = intval($n / $value);
// Concatenate characters
$result .= str_repeat($roman, $matches);
// Substract that from the number
$n = $n % $value;
}
return $result;
}
if (isset($_POST['submit'])) {
$n = $_POST['num'];
echo "Roman Letter for the given number ". $n . " is: " .numberToRoman($n);
return 0;
}
?>
</body>
</html>