Log in

View Full Version : How to check the frequency of an array in a txt?



ntin0s
03-06-2011, 01:55 AM
Hello ,

Can anyone tell me what I should use to check the frequency of an array that contains the alphabet in a txt file that contains words? Thanks a lot

djr33
03-06-2011, 03:24 AM
An array is not the same format as a txt file. It is a list of items, each of which may (or may not) be in the same format as the contents of the txt file. This format is called a string (basically "text" data).

If you can give us the exact formats you're talking about we can help.

Does the array represent a list of items that you want to track individually or as a whole?

ntin0s
03-06-2011, 07:51 PM
I want to count how many times the letters of the english alphabet are repeated in a .txt file which contains words in these format :

apple
add
banana
bird
coach
etc..

and output them like this:

a->2 times
b->15 times
etc

Nile
03-06-2011, 08:15 PM
This should do it:


<?php
function reoccurences($file){
if(!is_file($file)){ return false; }
$file = file_get_contents($file);
$reoccurences = array();
for($i = 0; $i < strlen($file); $i++){
$current = strtolower($file[$i]);
if(preg_match('/[a-zA-Z]/i', $current)){
if(isset($reoccurences[$current])){
$reoccurences[$current]++;
} else {
$reoccurences[$current] = 1;
}
}
}
ksort($reoccurences);
return $reoccurences;
}

print_r(reoccurences('file.txt'));
?>

bluewalrus
03-06-2011, 08:34 PM
<?php
$string = file_get_contents('file.txt');
$alphabet = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
for ($x= 0; $x< 26; $x++) {
$how_many = explode($alphabet[$x], strtolower($string));
echo $alphabet[$x] . "->" . (count($how_many) - 1) . "<br />";
unset($how_many);
}
?>


Oh, I'm a little late...

ntin0s
03-06-2011, 11:46 PM
Thanks both! Both works perfectly!:)

Nile
03-07-2011, 03:29 AM
No problem, I'm glad to help :D

Here on DD, we like to keep things organized. In an effort to do so, you have the option to set a thread to resolved when an issue is fixed. To make the status of the thread resolved:
1. Go to your first post
2. Edit your first post
3. Click "Go Advanced"
4. In the dropdown next to the title, select "RESOLVED"