Jump to content

Count words in array, sort and filter by variable occurences


Anti-Moronic

Recommended Posts

Say I have this array:

 

array(
0 => time
1 => time
2 => to
3 => to
4 => to
5 => fly
);

 

and 2 variables - $occMin and $occMax as number of occurrences.

 

If:

 

$occMin = 2;
$occMax = 3;

 

I want to produce sorted list with most occurrences at the top:

 

array(
0 => array('to', 3),
1 => array('time', 2)
);

 

My face just melted at the thought of even beginning to tackle this. Is this somewhat possible? would it require a monster function or am I missing some native php functions which could lend a hand?

Link to comment
Share on other sites

there is probably a much better way to do this but I program very simply, 'cos I have to debug it later !!

<?php
// test.php
$arr = array(
0 => 'time',
1 => 'time',
2 => 'to',
3 => 'to',
4 => 'to',
5 => 'fly'
);

$res = array();
foreach($arr as $val) {
if (count($res) == 0) {
	$res[$val] = 1;
} else {
	foreach($res as $key1=>$val1) {
		if ($val == $key1) {
			$res[$key1] = ($val1+1);
			break;
		}
		$res[$val] = 1;
	}
}
}
arsort($res);
foreach($res as $key=>$val) {
echo "<BR>".$key." appears ".$val." times";
}
die("<br>finished");
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.