How can a beginner optimize a PHP script that displays tag cloud keywords to handle a larger number of words efficiently?

When displaying a tag cloud with a large number of words, a beginner can optimize the PHP script by using an array to store the words and their frequencies, sorting the array based on the frequency, and limiting the number of words displayed to improve efficiency.

// Sample array of words with frequencies
$words = array(
    "apple" => 10,
    "banana" => 5,
    "orange" => 3,
    // Add more words and frequencies here
);

// Sort the array based on frequency in descending order
arsort($words);

// Limit the number of words displayed
$limit = 10;
$counter = 0;

echo "<div class='tag-cloud'>";
foreach ($words as $word => $frequency) {
    if ($counter < $limit) {
        $size = 12 + $frequency; // Adjust size based on frequency
        echo "<span style='font-size: {$size}px;'>{$word}</span>";
        $counter++;
    } else {
        break;
    }
}
echo "</div>";