Customizing SMF > Tips and Tricks

Roman Numerals

<< < (2/2)

Zencefil:

Many thanks to all of you guys! :D

Anguz:
I was thinking about the first part of the function. I guess that it could be required to feed it an int, instead of casting it, since the return value will be wrong most of the time if it wasn't an int to begin with... So I suggest that if not int, return false, and then do the roman numerals conversion and return the string. For more readability, you may want to put each array element in it's own line too.

--- Code: ---function Roman(\$arabic)
{
if (empty(\$arabic))
return;
if (!is_int(\$arabic))
return false;

\$arr = 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);
\$roman = '';

foreach (\$arr as \$a => \$n)
{
if (\$arabic < \$n)
continue;
if (\$a === 'M' || \$a === 'C' || \$a === 'X' || \$a === 'I')
{
\$roman .= str_repeat(\$a, floor(\$arabic / \$n));
\$arabic %= \$n;
continue;
}
\$roman .= \$a;
\$arabic -= \$n;
}

return \$roman;
}

--- End code ---