0

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.

2
  • Have you tried array_count_values(file($filename))? Commented May 18, 2012 at 20:50
  • Yes I have tried array count values, check the comment for the first answer to see my real issue. Commented May 18, 2012 at 20:57

1 Answer 1

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

arsort($counted);

  foreach($counted as $person => $count)
        echo "{$person} : {$count}<br />\r\n";
Sign up to request clarification or add additional context in comments.

5 Comments

Ok, I've gotten there, but what I really need to do is order by number of time each user shows up... Right now it is in order of what appears in the file.
Beat me to it. However expanding on your answer and sorting using the arsort function is simpler: foreach(array_count_values(file('file.txt')) as $person => $count){ $counts[$person] = $count; } arsort($counts); print_r($counts);
yes you right, bu don't forget use array_reverse after asort.
@TufanBarışYıldırım arsort is the reverse of asort. Great answer. Your implementation was few lines shorter than mine. +1
Tufan, your solution provided the number of the item in the array rather than the name of the user. (pastebin.com/DWFr6RCj), EmmanuelG's solution seemed to work fine! Thanks to you all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.