Going through array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jbriggsbloni
Forum Newbie
Posts: 1
Joined: Sat Jan 29, 2011 1:59 pm

Going through array

Post by jbriggsbloni »

I have an array of strings and a text file. I'm trying to see how many times each of the strings are in the text file (in .txt format). What is the best way to do this? Thanks for any help
User avatar
spedula
Forum Commoner
Posts: 81
Joined: Mon Mar 29, 2010 5:24 pm

Re: Going through array

Post by spedula »

I would open the file with fopen() and save the contents of is as $string. Then use substr_count() on that string.

Code: Select all

$filename = "something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

for($i = 0; $i < count($array); $i++) {
   echo $array[i]." occurs: ".substr_count($contents, $array[$i])." times in the file./n";
}
I haven't tested it but it should work or something very similar.
Post Reply