Haxor
Haxor

Reputation: 621

PHP: Count frequency of words

<?php
    $textarea = $_POST['textarea'];
    $text = array($textarea);
    if (isset($_POST["submit_btn"])) {
        $submit = $_POST['submit_btn'];
        echo $textarea;
        echo "<br />";
        echo str_word_count($textarea);
        $arr = explode(' ', $textarea);
        $arr1 = array_count_values($arr);
        echo " words <br />";
        foreach ($arr1 as $k => $v) {
            echo "$k -- $v <br />";
        }

    }
    ?>

But I am not allowed to use str_word_count and array_count_values...

Upvotes: 0

Views: 251

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Since this is homework, try this approach:

  1. Create an associative array at the start of your loop.
  2. Split the content by space.
  3. For each word in the content, check if the word is already a key in the associative array, if it is add +1 to the value of the key, otherwise set the value of the key to 1.

At the end, print your associative array.

Upvotes: 5

Related Questions