arrays - Compute the most commonly occuring lines in a file using PHP? -


i have php script appends string end of file. able read file , find out number of times each line occurs, , compute commonly occuring lines , thier numbers. example, if have:

williamtdr chicken chicken williamtdr williamtdr pig 

i get:

williamtdr, 3 chicken, 2 pig, 1 

is there way in php?

thanks!

//$data = file_get_contents('yourfile.txt'); // file contents $data = 'williamtdr chicken chicken williamtdr williamtdr pig';  $data = explode("\n", $data); // split data @ each newline $data = array_count_values($data); // count occurrences of each line  print_r($data); 

will output:

array (     [williamtdr] => 3     [chicken] => 2     [pig] => 1 ) 

[ demo ]


if want same output in question loop on so:

foreach ($data $word => $count) {     echo $word . ', ' . $count . "\n"; } 

alternatively, , better way:

$data = file('yourfile.txt', file_ignore_new_lines | file_skip_empty_lines); $data = array_count_values($data); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -