Trying to take numbers from a text file and see how many times they occur. I've gotten to the point where I can print all of them out, but I want to display just the number once, and then maybe the occurrences after them (ie: Key | Amount; 317 | 42). Not looking for an Answer per se, all learning is good, but if you figure one out for me, that would be awesome as well!
-
Show us what you've got so far, and we can offer better advice.Ryre– Ryre2011-03-22 18:59:52 +00:00Commented Mar 22, 2011 at 18:59
-
$numbers=file_get_contents('names.txt'); $convert = explode(" ", $numbers); for ($i=0;$i<count($convert);$i++) { //sort values in array asc. echo $convert[$i]."<br />"; } so far, it just lists the numbers to the screen for my convenience.Dysfunctionator– Dysfunctionator2011-03-24 12:09:12 +00:00Commented Mar 24, 2011 at 12:09
3 Answers
preg_match_all will return the number of matches against a string.
$count = preg_match_all("#$key#", $string);
print "{$key} - {$count}";
4 Comments
preg_match_all here, you'd first have to get a list of all the unique words in the file. While you're in the process of doing that you can easily count their occurrences. Running preg_match_all after you've gotten the list would just be wasteful.So if you're already extracting the data you need, you can do this using a (fairly) simple array:
$counts = array();
foreach ($keysFoundFromFile AS $key) {
if (!$counts[$key]) $counts[$key] = 0;
$counts[$key]++;
}
print_r($counts);
If you're already looping to extract the keys from the file, then you can simply assign them directly to the $counts array without making a second loop.
Comments
I think you're looking for the function substr_count().
Just a heads up though, if you're looking for "123" and it finds "4512367" it will match it as part of it. The alternative would be using RegEx and using word boundaries:
$count = preg_match_all('|\b'. preg_quote($num) .'\b|', $text);
(preg_quote() for good practice, \b for word boundaries so we can be assured that it's not a number embedded in another number.)