简体   繁体   中英

While loop - possible to have only 6 loops?

This is my code, I would like it so that it only does the first 6 array items. Also, how would I write a loop for everything AFTER the 6 first array items?

while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {

    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}

Try the following for your first request:

$count = 0;
while($servdescarrayrow = mysql_fetch_array("servdescarray")) {
  $count++;
  echo "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
  if($count == 6){
    break;
  }
}

Then you could do the below for part 2:

$count = 0;
while($servdescarrayrow = mysql_fetch_array("servdescarray")) {
  $count++;
  if($count > 6){
    echo "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
  }
}

Alternatively (and better) is to use LIMIT in your SQL query

To have just the first 6 rows, the best way is to use LIMIT in your sql statement in this way.

SELECT *
FROM table
WHERE condition
LIMIT 6

If you want to have a loop that print the first 6 rows and then another loop that will print the remaining rows use the solution provided by nickb .

for( $i = 0; $i < 6; $i++)
{
    $servdescarrayrow = mysql_fetch_array("servdescarray");
    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}

To get the remaining entries (since the result set will remember where it left off):

while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {

    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}
SELECT * 
FROM table 
WHERE condition 
OFFSET 6 

this query will get everything after the first 6. I'm assuming you're using mysql.

Adding a single loop approach. To keep it simple and readable, us a count variable $rowNum to determine what to do in your loop.

    $rowNum = 0;
    while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {
        $rowNum++;

        if($rowNum<=6)
        {
             ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
        }
        else
        {
            // Code for other items
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM