tags:

views:

41

answers:

3

Hi all

I have an array of tags taken from a MySQL database. Obviously, these tags are strings and are stored in an array, with one element in the array storing each tag. TO build my tag cloud, I want to be able to count the occurrences of each tag to find the most common tag.

For example, if I have the table below...

tag1
tag1
hi
bye
gnu
tux
tag1
tux
tux
tag1
...
etc

... the most commonly occurring tag is "tag1" what I want to do is count how many times that tag occurs in the array. Max() doesn't help here due to it only liking numerical values.

Can anyone help?

Thanks,

James

+8  A: 

use array_count_values

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>


Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

http://php.net/manual/en/function.array-count-values.php

if you want not case sensetive version use :

$ar = array_count_values(array_map('strtolower', $ar));
Haim Evgi
Perfect - thanks!
JamWaffles
+4  A: 

I suspect you could have your database perform all the heavy lifting for you. Sounds like you are getting an array of tags, maybe like this

SELECT tag FROM mytable;

But you could do this

SELECT tag,count(*) AS occurrences FROM mytable 
GROUP BY tag
ORDER BY occurences;

Hey presto, a list of tags and their frequency!

Paul Dixon
+1 for the better solution
taspeotis
actually the tags are stored as a CSV list in the database, but yeah I do get an array of them - `explode()` comes in very handy! (PHP)
JamWaffles
Also, I used the solution I marked correct, but when the time comes to have a good rewrite fest, I will definitely use this method - thank you.
JamWaffles
A: 

if you array is like this

$array = array('tag1','tag1','hi','bye','gnu','tux','tag1','tux','tux','tag1');

$arrayCounting = array_count_values($array));

will give you an array like this to work with

Array
(
    [tag1] => 4
    [hi] => 1
    [bye] => 1
    [gnu] => 1
    [tux] => 3
)
Shaun Hare