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.