Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
PHP Roman Numerals Code Kata solution. A collaborative effort of the people @ PHP User Group Rheinhessen, Jan '13.
<?php
/**
* Converts Roman numbers to integers
*/
class Roman
{
/**
* @var array
*/
protected $d = array(
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
);
/**
* @param string $roman
*/
public function toInt($roman)
{
$res = 0;
$chars = str_split($roman);
$length = count($chars);
for ($i = 0; $i < $length; $i++) {
if (isset($chars[$i+1]) && $this->d[$chars[$i+1]] > $this->d[$chars[$i]]) {
$res -= $this->d[$chars[$i]];
} else {
$res += $this->d[$chars[$i]];
}
}
return $res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment