Playing with Roman numerals

The following code returns the longest Roman numeral string generated for the year between 1 and 2099. Note that the largest number that can be represented in Roman notation is 3,999 (MMMCMXCIX).

function integerToRoman($year)
    /* Ref: 
    $result = '';

    // Create a lookup array that contains all of the Roman numerals.
    $lookup = 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
    foreach($lookup as $roman => $value)
        // Determine the number of matches
        $matches = intval($year / $value);

        // Add the same number of characters to the string as the count of $matches
        $result .= str_repeat($roman,$matches);

        // Set the $year to be the remainder of the $year and the value
        $year = $year % $value;
    return $result;

$longest = '';
$year = '';

for($i=1; $i <= 2099; $i++) {
    $roman = integerToRoman($i);
    if(strlen($roman) > strlen($longest)) {
        $longest = $roman;
        $year = $i;

echo $longest . " : " . $year;


That will be year 1888, represented by the Roman string ‘MDCCCLXXXVIII’, which is 13 characters long. The next longest Roman number is 2888 represented by ‘MMDCCCLXXXVIII’ which has has 14 characters.

Building a Graph data structure in PHP

undirected graphGraphs are one of the most frequently used data structures,along with linked lists and trees. In a recent PHP project I needed to build a Graph structure to analyze some interlinked urls. The problem was of a simple nature, so rather than writing my own code, I went with the one available in the Pear repository.

The Pear Structures_Graph package allows creating and manipulating graph data structures. It allows building of either directed or undirected graphs, with data and metadata stored in nodes. The library provides functions for graph traversing as well as for characteristic extraction from the graph topology.
Read More

Linked List implementation in PHP

Data structures are one of the core elements of computer science and they are also fun to program. But being a web developer the opportunity for implementing them in any application is quite rare. But then I thought, What the heck! I can just code for the joy of it, and it will also help me brush up on my DS skills. So here it is, a single linked list implementation in PHP for whoever may care. I will be posting other data structure and algorithm implementations here, so keeping watching. The code is given below.
Read More