beachcoder.co.uk

7Mar/11Off

PHP and Roman Numerals

After hunting around for functions that convert Arabic numbers to Roman numerals and vice versa, everything I found was huge (~100 lines) except for one very graceful function to convert Arabic numbers to Roman numerals. So I combined it with my own Roman to Arabic converter.

Pass it an int, a numeric string or a string of Roman numerals, and it will convert from one to the other.

Feel free to use the function in your own projects, but please keep the attributions intact.

function roman($num){
	$result='';
	$numerals=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
	);
	if(preg_match('/^[0-9]+$/',$num)){
		// To Roman: www.go4expert.com/forums/showthread.php?t=4948
		$n=intval($num);
		foreach($numerals as $roman=>$value){
			$matches=intval($n/$value);
			$result.=str_repeat($roman,$matches);
			$n=$n%$value;
		}
	}else{
		// To Arabic: www.beachcoder.co.uk/php-and-roman-numerals/
		$num=strtoupper($num);
		for($i=0;$i<strlen($num);$i++){
			$letter=$num[$i];
			$next=$num[$i+1];
			if($next&&$numerals[$next]>$numerals[$letter]){
				$result+=$numerals[$next]-$numerals[$letter];
				$i++;continue;
			}
			$result+=$numerals[$letter];
		}
	}
	return $result;
}

// Usage
echo roman('1000'); // M
echo roman(1100);   // MC
echo roman('MC');   // 1100
Filed under: PHP Comments Off