Bojangles
Bojangles

Reputation: 101513

Finding the values in an array that have the most occurrences

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.

Upvotes: 2

Views: 3727

Answers (3)

Haim Evgi
Haim Evgi

Reputation: 125584

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 do not want the case-sensitive version use :

$ar = array_count_values(array_map('strtolower', $ar));

Upvotes: 9

Shaun Hare
Shaun Hare

Reputation: 3871

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
)

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300975

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!

Upvotes: 5

Related Questions