Subscribe to atik's Blog        RSS Feed
-----

Word Counter Class in PHP

Icon Leave Comment
Lets see how to code a word counter class in PHP. This class will count the number of occurrence of each word in a file. The code is simple and quite self-explanatory.

<?php
class WordCounter
{
    const ASC="ascending";      //ascending order
    const DESC="descending";    //descending order
    private $words;

    function __construct($file_name)
    {
        $file_words=file_get_contents($file_name);  
        $file_words=strtolower($file_words);           
        $words_array=str_word_count($file_words,1);     //returning array of each words in the string
        $this->words=array_count_values($words_array); 
    }

    function count($order)
    {
        if($order==self::ASC)
        {
            asort($this->words);
        }

        else if($order==self::DESC)
        {
            arsort($this->words);
        }

        foreach($this->words as $key=>$value)
        {
            echo "{$key}-{$value}<br/>";
        }
    }
}
?>



Example:

$a=new WordCounter("welcome.txt");
$a->count(WordCounter::DESC);

0 Comments On This Entry

 

April 2014

S M T W T F S
  12345
6789101112
13141516171819
20 212223242526
27282930   

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)