PHP function to print a tag cloud


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function printTagCloud($tags) {
  2. // $tags is the array
  3.  
  4. arsort($tags);
  5.  
  6. $max_size = 32; // max font size in pixels
  7. $min_size = 12; // min font size in pixels
  8.  
  9. // largest and smallest array values
  10. $max_qty = max(array_values($tags));
  11. $min_qty = min(array_values($tags));
  12.  
  13. // find the range of values
  14. $spread = $max_qty - $min_qty;
  15. if ($spread == 0) { // we don't want to divide by zero
  16. $spread = 1;
  17. }
  18.  
  19. // set the font-size increment
  20. $step = ($max_size - $min_size) / ($spread);
  21.  
  22. // loop through the tag array
  23. foreach ($tags as $key => $value) {
  24. // calculate font-size
  25. // find the $value in excess of $min_qty
  26. // multiply by the font-size increment ($size)
  27. // and add the $min_size set above
  28. $size = round($min_size + (($value - $min_qty) * $step));
  29.  
  30. echo '<a href="#" style="font-size: ' . $size . 'px" title="' . $value . ' things tagged with ' . $key . '">' . $key . '</a> ';
  31. }
  32. }
  33.  
  34. $tags = array('weddings' => 32, 'birthdays' => 41, 'landscapes' => 62, 'ham' => 51, 'chicken' => 23, 'food' => 91, 'turkey' => 47, 'windows' => 82, 'apple' => 27);
  35.  
  36. printTagCloud($tags);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.