3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace JoshDiFabio; interface RomanNumeralGeneratorInterface { /** * @param int $number * @return string * @throws \InvalidArgumentException Argument not an integer or out of range * @author Josh Di Fabio <joshdifabio@hotmail.com> */ public function generate($number); } class RomanNumeral { const ONE = 'I'; const FIVE = 'V'; const TEN = 'X'; const FIFTY = 'L'; const ONE_HUNDRED = 'C'; const FIVE_HUNDRED = 'D'; const ONE_THOUSAND = 'M'; } class RomanNumeralGenerator implements RomanNumeralGeneratorInterface { /** * @var array * @author Josh Di Fabio <joshdifabio@hotmail.com> */ private $_integerNumeralMap = array( 1000 => RomanNumeral::ONE_THOUSAND, 500 => RomanNumeral::FIVE_HUNDRED, 100 => RomanNumeral::ONE_HUNDRED, 50 => RomanNumeral::FIFTY, 10 => RomanNumeral::TEN, 5 => RomanNumeral::FIVE, 1 => RomanNumeral::ONE, ); /** * @param int $number * @return string * @throws \InvalidArgumentException Argument not an integer or out of range * @author Josh Di Fabio <joshdifabio@hotmail.com> */ public function generate($number) { if (!is_integer($number)) { throw new \InvalidArgumentException('Provided argument is not an integer.'); } if (1 > $number || 3999 < $number) { throw new \InvalidArgumentException( 'The provided number is not within the allowed range of 1 to 3999.'); } $numerals = array(); while (0 < $number) { foreach ($this->_integerNumeralMap as $_integer => $_numeral) { if ($number >= $_integer) { $numerals[] = $_numeral; $number -= $_integer; break; } } } return implode('', $numerals); } }

preferences:
37.35 ms | 402 KiB | 5 Q