- var_dump: documentation ( source)
- floor: documentation ( source)
- dechex: documentation ( source)
- max: documentation ( source)
- min: documentation ( source)
- sprintf: documentation ( source)
<?php
function word_cloud($words, $div_size = 400) {
$tags = 0;
$cloud = "<div style=\"width: {$div_size}px\">";
/* This word cloud generation algorithm was taken from the Wikipedia page on "word cloud"
with some minor modifications to the implementation */
/* Initialize some variables */
$fmax = 96; /* Maximum font size */
$fmin = 8; /* Minimum font size */
$tmin = min($words); /* Frequency lower-bound */
$tmax = max($words); /* Frequency upper-bound */
foreach ($words as $word => $frequency) {
if ($frequency > $tmin) {
$font_size = floor( ( $fmax * ($frequency - $tmin) ) / ( $tmax - $tmin ) );
/* Define a color index based on the frequency of the word */
$r = $g = 0; $b = floor( 255 * ($frequency / $tmax) );
$color = '#' . sprintf('%02s', dechex($r)) . sprintf('%02s', dechex($g)) . sprintf('%02s', dechex($b));
}
else {
$font_size = 0;
}
if ($font_size >= $fmin) {
$cloud .= "<span style=\"font-size: {$font_size}px; color: $color;\">$word</span> ";
$tags++;
}
}
$cloud .= "</div>";
return array($cloud, $tags);
}
$words = ['una' => 1, 'dos' => 2, 'qweqwe' => 3];
var_dump(word_cloud($words));