basically i am trying to create a function that will turn a Roman numeral into a integer.
I have an array:
$roman_numerals=[
'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
];
I'm fairly new to PHP so i'm still getting used to the way of think so please bear in mind i'm still learning :)
here is my function - or what i have so far:
//Array
function romanToInteger($key)
{
$roman_numerals=[
'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
];
$roman = intval($key);
$result = 0;
foreach ($roman_numerals as $key => $value) {
while (strpos($roman, $key) === 0) {
$result += $value;
$roman = substr($roman, strlen($key));
}
}
var_dump($roman); //test
echo $result;
}
i have been at this for hours and would just like the see the light of it, any advice would be greatly appreciated.
when i run it in the command line with
echo romanToInteger('I');
i just get returned 0 and i think its something to do with my intval?
Sorry again for being a noob, help appreciated though or any pointers! :)
Yes it has something to do with the intval
.
You're basically casting your roman input into an integer rendering it into 0
.
Remove that:
function romanToInteger($key)
{
$romans = [
'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,
];
$roman = $key;
$result = 0;
foreach ($romans as $key => $value) {
while (strpos($roman, $key) === 0) {
$result += $value;
$roman = substr($roman, strlen($key));
}
}
echo $result;
}
romanToInteger('IV');
Sample Output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With