Wolvy Wolvy -4 years ago 93
PHP Question

Sum all values found in a text file and store them using Array_count_values in php

well, im a newbie in php, so i was making a program that counts words from a specific text file.
This is my text file:

Hello Hello Hello Hello
Hello Word array sum
Hello Find


This is my code (php:

/*Open file*/
$handle = fopen($_FILES['file']['tmp_name'], 'r');

/*read all lines*/
while (! feof($handle)) {
$line = fgets($handle);

/*using array_count_values with str_word_count to count words*/
$result= (array_count_values(str_word_count(strip_tags(strtoupper($line)), 1)));

/*sort array*/
arsort($result);

/*show the first ten positions and print array*/
$top10words2 = array_slice($result, 0, 10);
print "<pre>";
print_r ($top10words2);
print "</pre>";
}
fclose($handle);


but my output is like this:

Array{
[Hello] => 4
}
Array{
[Hello] => 1
[Word] => 1
[array] => 1
[sum] => 1
}
Array{
[Hello] => 1
[Find] => 1
}


I need the output to be like this:

Array{
[Hello] => 6
[Word] => 1
[array] => 1
[sum] => 1
[find] => 1
}


Any tips?

Answer Source

I agree with the file_get_contents() answer from Ayaou, however for very large files you may need to do it as you've started. You want to build the array of words in the loop and then count, sort and slice afterward:

$result = array();
while(!feof($handle)) {
    $line = fgets($handle);
    $result = array_merge($result, str_word_count(strip_tags(strtoupper($line)), 1));
}
$result = array_count_values($result);
arsort($result);
$top10words2 = array_slice($result, 0, 10);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download