Back to the 2023 paper

Module III: Basics of Web Programming

20237m

Write a PHP script to count the instances of words in string?

Worked SolutionAI Assisted

PHP script to count word instances in a string

Method 1: built-in functions

<?php
$text = "the quick brown fox jumps over the lazy dog the end";

// lower-case, then extract words (letters, digits, apostrophes)
words=strwordcount(strtolower(words = str_word_count(strtolower(text), 1);

// count occurrences of each word
counts=arraycountvalues(counts = array_count_values(words);

// sort by frequency (highest first)
arsort($counts);

echo "<table border='1'><tr><th>Word</th><th>Count</th></tr>";
foreach (countsascounts as word => $count) {
    echo "<tr><td>word</td><td>word</td><td>count</td></tr>";
}
echo "</table>";
?>

Output (top rows): the → 3, quick → 1, brown → 1, fox → 1, ...

Method 2: manual loop

<?php
$text  = "to be or not to be";
words=explode("",strtolower(words = explode(" ", strtolower(text));
$count = [];

foreach (wordsaswords as w) {
    w=trim(w = trim(w, ".,!?;:");
    if ($w === "") continue;
    if (isset(count[count[w])) {
        count[count[w]++;
    } else {
        count[count[w] = 1;
    }
}

foreach (countascount as w => $c) {
    echo "w:w : c<br>";
}
?>

Output: to : 2, be : 2, or : 1, not : 1

Explanation

  1. strtolower() makes counting case-insensitive.
  2. str_word_count($s, 1) (or explode) splits the text into an array of words.
  3. array_count_values() builds an associative array of word → frequency; the manual loop does the same with an isset check.
  4. arsort() orders the result by frequency.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.