Jump to content

While and For loops


monkeytooth

Recommended Posts

Ok, I have a loop running. Works fine. But now I want to add a hr tag between results. Which that I can do, what I can't do though is figure out how to find if while the loop is running if the result being echoed out is the last one or not. Because I don't want an hr under the last result.

 

So is there any way to determine the last result in a loop and remove an element from it in such a way?

Link to comment
https://forums.phpfreaks.com/topic/193481-while-and-for-loops/
Share on other sites

while($results = mysql_fetch_array($display_result)) {
/*code to repeat omitted*/
}

 

I should have added this with my original post. I am taking info out of a DB, to which a static count does not exist. I could show 3 results I could show 50 pending on the query. So I wouldnt be able to set an if statement on it with a set number. So is there a way to find the last entry in a loop built like above and remove a piece from it as previously asked? Or am I just shooting in the dark for hopes..  :D

Link to comment
https://forums.phpfreaks.com/topic/193481-while-and-for-loops/#findComment-1018745
Share on other sites

Just use a counter and compare with the total records returned from the query using mysql_num_rows() as jl5501 suggests above. Another option is to put the results into an array and implode() the array with whatever divider you want.

 

Exmple #1:

$totalRows = mysql_num_rows($result);
$rowCount = 0;
while($row = mysql_fetch_assoc($result))
{
    $rowCount++;
    //Echo the results
    echo "{$row['somedata']}<br />\n";
  
    if ($rowCount < $totalRows)
    {
        echo "<hr>\n";
    }
}

 

 

Exmple #2:

$outputArray = array();
while($row = mysql_fetch_assoc($result))
{
    //Add data to result array
    $outputArray[] =  "{$row['somedata']}<br />\n";
}

//Echo output
echo implode("<hr>\n", $outputArray);

Link to comment
https://forums.phpfreaks.com/topic/193481-while-and-for-loops/#findComment-1018755
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.