Keenan Thompson
Keenan Thompson

Reputation: 980

PHP - Count number of times string appears in file

I've got a file (leaderboard.txt) that looks like this:

funkystudios
funkystudios
funkystudios
gilletteracer74
axehairgel
Ferby123
dirdam
TheWu13
Expert_Assassin
TheWu13
ocanosoup

I want to be able to read this file, and print out the number of times each person appears in the file. (Also place in order of # of times in file)

funkystudios: 3
TheWu13: 2
gilletteracer74: 1
axehairgel: 1
(and so on)

I've tried various ways but It all came down to an issue when I would try to order them correctly... I'm guessing there is a pretty easy way to do this. (I'm new to PHP...)

EDIT: I have gotten to this point:

  foreach(array_count_values(file('leaderboard.txt')) as $person => $count)
echo "{$person} : {$count}<br />\r\n";

It doesn't order by the $count, but simply who comes up first in the file.

Upvotes: 0

Views: 2197

Answers (1)

$counted = array_count_values(file('leaderboard.txt'));

arsort($counted);

  foreach($counted as $person => $count)
        echo "{$person} : {$count}<br />\r\n";

Upvotes: 6

Related Questions