Search code examples
phploopsdo-whiletag-cloud

Why doesn't my loop echo for all iterations?


I'm trying to make a tag cloud system getting its values from PHP/SQL but it seems to work erratically, only giving a handful of the expected results. What's causing this odd behaviour?

As far as I can tell it should loop through a total of 20 times (0-19) and each time it adds a string into an array.

The system starts out by getting the 20 most popular tags from my database in descending order, once its got this I create a string and set the font size. This string is then stored in an array and is echoed out using a random number array giving a random order to the cloud.

I then increase the value of i for my loop iteration whilst decreasing the font size for the next less popular tag.

<h1>Tag Cloud</h1>
    <?php
        $sql = "SELECT * FROM tags ORDER BY count DESC";
        $tags_query = mysqli_query($db_conx, $sql);           
        $i = 0;
        $tag_array = array();
        $tag_size_max = 36;
        $tag_size_min = 16;

        $numbers = range(0, 19);
        shuffle($numbers);

        do {
            $row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
            $tag = $row["tag"];  
            $tag_count = $row["count"];             


            $tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";

            echo $tag_array[$numbers[$i]];

            $i++;
            $tag_size_max--;    

        } while ($i < 20);
    ?>

You can see it kind of working in the footer of my site http://www.vwrx-project.co.uk


Solution

  • It seems that you're trying to echo $tag_array element with index which isn't yet in the array itself. You would probably need two loops - first to fill the $tag_array, and another one to echo them.

    Do you have proper ERROR_LEVEL - there should be some notices about missing indexes - at least if I'm ready your code correctly ;)

    Something like this:

    // fill the array
    for ($i=0; $i<20; $i++) {
        $row = mysqli_fetch_array($tags_query, MYSQLI_ASSOC);
        $tag = $row["tag"];  
        $tag_count = $row["count"]; // this seems to be unused
        $tag_array[] = "<p style='font-size:".$tag_size_max."px; padding:0px;'>".$tag."</p>";
    }
    
    // echo the array
    for ($i=0; $i<count($tag_array); $i++) {
        echo $tag_array[$numbers[$i]]; 
    }