Here is another post containing a snippet of code that you can use in your own project or just so that you can store it in your "Useless Snippets Folder" on your Desktop. You can view all of the older code snippet articles by browsing the code snippet category list.

This code can be used to make a simple and easy tag cloud for your categories or tags on your own website or blog. It uses a simple mathematical sum to calculate a percentage for the font size of each tag and then returns it in a XHTML-compliant, inline list. The function requires an array of the tags in the format: "$tags['tag_name'] = tag_count;", when tag_name is the name of the tag and tag_count is the amount of instances the tag has.

Anyway, here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
function tag_cloud($tags) {
	if (!$tags) {
		return false; // Error: no $tag argument was specified.
	}
 
	$max_size = 250;
	$min_size = 100;
 
	$largest = max(array_values($tags));
	$smallest = min(array_values($tags));
 
	$range = $largest - $smallest;
	if ($range == 0) {
		$range = 1;
	}
 
	$step = ($max_size - $min_size) / ($range);
 
	$content = '<ul style="list-style: none; padding: 0; margin: 0;">';
	foreach ($tags as $key => $value) {
 
		$size = $min_size + (($value - $smallest) * $step);
 
		$content .= '<li style="display: inline; padding: 5px;"><a href="#" style="font-size: ' . $size . '%" title="'. $key . ' (' . $value . ')">' . $key . '</a></li>';
	}
	$content .= '</ul>';
 
	return $content; // Return: return the output content, conating the formatted tags.
}
?>

For example, you could use the function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$tags['tag1'] = 21;
$tags['tag2'] = 54;
$tags['tag3'] = 42;
$tags['tag4'] = 12;
$tags['tag5'] = 32;
$tags['tag6'] = 12;
$tags['tag7'] = 54;
$tags['tag8'] = 35;
 
echo tag_cloud($tags);
?>

Which would output the following: