3

I was wondering how I could search some words, and get the results of how many where counted in a file. I've already integrated it where it counts all lines, so that it checks each word in every line. But I'm having problems counting how many times one of the words contains in a line.

Lets say the text file looks something like this:

cars have wheels
you can drive cars
1337 is Leet
the beauty of cars
too much cars
something else
good breakfast could be eggs
eggs does not smell good
flying cars could be the future

And I want the array to look like this:

words = cars,eggs,1337

array{
    "cars" => 5,
    "eggs" => 2,
    "1337" => 1
}

And I've setup this code so far:

$words = explode(',', 'word1,word2,word3');

$handle = fopen('/path/to/file.txt', "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        foreach ($words as $value => $number) {
            if (strpos($line, $value) !== false) {
                $words[$number] = $words[$number] + 1;
            }
        }
    }

    fclose($handle);
}

var_dump($words)

this code outputs:

array(1) { 
    [0]=> array(3) { 
        [0]=> string(10) "cars" 
        [1]=> string(9) "eggs" 
        [2]=> string(10) "1337" 
    } 
}

I know that I don't need to do this for each line, but it's more code which I removed from this question (including counting and echo in a certain way). And it seems like I'm doing it wrong at the part where I should add +1 to each word, but I just don't understand how to deal with arrays properly.

Typewar
  • 825
  • 1
  • 13
  • 28
  • 1
    Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please [edit] these details in or we may not be able to help. – Blue Jun 25 '17 at 09:19
  • 2
    Voted `reopen` because the problem is more related to how PHP arrays work than counting words in a line – Déjà vu Jun 25 '17 at 09:34
  • See answer : https://stackoverflow.com/questions/11135085/count-unique-appearance-of-substring-in-a-list-of-words-without-knowing-the-subs – Niv Apo Jun 25 '17 at 16:22

0 Answers0