Dictionaries in PHP

I was bored tonight and started watching some David Malan’s CS50 classes again so I figure make a quick post about it. Here is one of his PHP code samples I like. David also make use of short tags if the <? ?> looks a little weird to you. This example is from his week 9 Monday class and feel free to watch his video for a better explanation of PHP then I could provide.

Fall 2011 Week 9 – Monday

Also if your interested in learning PHP, check out their documentation at PHP: Hypertext Preprocessor

<?
/***********************************************************************
* dictionary.php
*
* Computer Science 50
* David J. Malan
*
* Implements a dictionary.
**********************************************************************/

// size of dictionary
$size = 0;

// dictionary
$dictionary = array();

/*
* bool
* check($word)
*
* Returns true if word is in dictionary else false.
*/

function check($word)
{
    global $dictionary;
    if ($dictionary[strtolower($word)])
        return true;
    else
        return false;
}

/*
* bool
* load($dict)
*
* Loads dict into memory. Returns true if successful else false.
*/

function load($dict)
{
    global $dictionary, $size;
    if (!file_exists($dict) && is_readable($dict))
        return false;lectures/9/src9/mispellings/dictionary.php
    foreach (file($dict) as $word)
    {
        $dictionary[chop($word)] = true;
        $size++;
    }
    return true;
}

/*
* int
* size()
*
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/

function size()
{
    global $size;
    return $size;
}

/*
* int
* unload()
*
* Unloads dictionary from memory. Returns true if successful else false.
*/
function unload()
{
    return true;
}

?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s