How to create a tag cloud by wrapping array values in h1 through h6 tags in PHP

2 Answers

0 votes
$arr = array("aa", "bbb", "cccc", "ddddd", "eeeeee", "fffffff", "gggggggg");
$weight = array(6, 3, 8, 3, 1, 2, 1);
$highest = max($weight);

for ($x = 0; $x < count($arr); $x++) {
    $normalized = $weight[$x] / $highest;
    $heading = ceil($normalized * 6); 
    echo "<h".$heading.">".$arr[$x]."</h".$heading.">" . "\n";
}



/*
run:

<h5>aa</h5>
<h3>bbb</h3>
<h6>cccc</h6>
<h3>ddddd</h3>
<h1>eeeeee</h1>
<h2>fffffff</h2>
<h1>gggggggg</h1>

*/

 



answered 8 hours ago by avibootz
0 votes
// Array of tags where the key is the tag name
// and the value is its weight (e.g., frequency or popularity)
$tags = [
    "php" => 25,
    "javascript" => 40,
    "html" => 10,
    "css" => 5,
    "mysql" => 18,
    "typescript" => 30
];

// Determine the smallest and largest weights.
// These help us scale values proportionally.
$min = min($tags);
$max = max($tags);

foreach ($tags as $tag => $count) {

    // If all values are identical, avoid division by zero
    // and assign a neutral heading level.
    if ($max == $min) {
        $level = 3;
    } else {
        // Scale the weight to a heading level (1–6)
        // Highest weight → h1
        // Lowest weight → h6
        // Everything else is mapped proportionally.
        $level = 6 - floor(5 * ($count - $min) / ($max - $min));
    }

    // Output the tag wrapped in the calculated heading level
    echo "<h{$level}>{$tag}</h{$level}>\n";
}



/*
run:

<h4>php</h4>
<h1>javascript</h1>
<h6>html</h6>
<h6>css</h6>
<h5>mysql</h5>
<h3>typescript</h3>

*/

 



answered 8 hours ago by avibootz

Related questions

...