Search code examples
phpstringcountword-count

Can someone explain to me this 'counting sentences' php code?


I have a task to count sentences without using str_word_count, my senior gave it to me but I am not able to understand. Can someone explain it?

I need to understand the variable and how it works.

<?php

$sentences = "this book are bigger than encyclopedia";

function countSentences($sentences) {
    $y = "";
    $numberOfSentences = 0;
    $index = 0;

    while($sentences != $y) {
        $y .= $sentences[$index];
        if ($sentences[$index] == " ") {
            $numberOfSentences++;
        }
        $index++;
    }
    $numberOfSentences++;
    return $numberOfSentences;
}

echo countSentences($sentences);

?>

The output is

6


Solution

  • It's something very trivial, I'd say. The task is to count words in a sentence. A sentence is an string (a sequence of characters) that are letters or white spaces (space, new line, etc.)...

    Now, what's a word of the sentence? It is a distinct group of letters that "don't touch" other group of letters; meaning words (group of letters) are separated from each other with white space (let's say just a normal blank space)

    So the simplest algorithm to count words consist in: - $words_count_variable = 0 - go through all the characters, one-by-one - each time you find a space, it means a new word just ended before that, and you have to increase your $words_count_variable - lastly, you'll find the end of the string, and that means a word just ended before that, so you'll increase for the last time your $words_count_variable

    Take "this is a sentence".

    We set $words_count_variable = 0;
    
    Your while cycle will analyze:
    "t"
    "h"
    "i"
    "s"
    " " -> blank space: a word just ended -> $words_count_variable++ (becomes 1)
    "i"
    "s"
    " " -> blank space: a word just ended -> $words_count_variable++ (becomes 2)
    "a"
    " " -> blank space: a word just ended -> $words_count_variable++ (becomes 3)
    "s"
    "e"
    "n"
    ...
    "n"
    "c"
    "e"
    -> end reached: a word just ended -> $words_count_variable++ (becomes 4)
    

    So, 4. 4 words counted.

    Hope this was helpful.