avo Posted March 6, 2008 Share Posted March 6, 2008 Hi all Can anyone help me out please Im looping and echoing an array foreach ($colours as $hex) { echo '<td bgcolor="'.$hex.'"><input type="radio" name="bcolour" id="bcolour" value="'.$hex.'"></td>' ; } but within the loop i need to echo the table elements <tr> (4 td's from above) </tr> so at the start of the loop i need <tr> loop four times then </tr> continue doing this untill the loop is finished if the loop is finished after only two <td></td> (for example echo </tr> hope this makes sense Help appriciated. Quote Link to comment Share on other sites More sharing options...
deadonarrival Posted March 6, 2008 Share Posted March 6, 2008 <?php //Iterations done $i = 0; //Walk through the array foreach ($colours as $hex) { //Add 1 to i $i++; //If it's the first in a row if($i == 0) { //Start a row echo "<tr>"; //Store that we're currently in a row $open = true; } //Do our normal thing echo '<td bgcolor="'.$hex.'"><input type="radio" name="bcolour" id="bcolour" value="'.$hex.'"></td>' ; //If it's the last in the row (or, for some reason, past it) if($i >= 4) { //Close the row echo "</tr>"; //Start again $i = 0; //Make sure we know we have a full row. $open = false; } } //Oops, what if the tr is still open? It'll ruin the layout! //If we still have an open row... if($open == true) { //Count down from 4 to $i, and make 4 new (empty) cells, so we don't break the layout for($f=4;$f=$i;$i--) { echo "<td> </td>"; } //Then close the row properly. echo "</tr>"; } ?> This could be done with a for loop too, but I've already written the above example (untested) which does the job too. I'll rewrite later if I remember Quote Link to comment Share on other sites More sharing options...
Agricola Posted March 6, 2008 Share Posted March 6, 2008 create a counter to count the TDs , set this to 0 outside the for each, every time get to 4 output </tr> reset counter to 0, if counter 0 output <tr> after loop finish outputting empty <td></td> to make it complete. <?php $td_counter=0; foreach ($colours as $hex) { if ($td_counter == 0){ echo "<tr>";} $td_counter++; echo '<td bgcolor="'.$hex.'"><input type="radio" name="bcolour" id="bcolour" value="'.$hex.'"></td>' ; if ($td_counter == 4){ echo "</tr>"; $td_counter==0; } } if ($td_counter > 0 ){ for ($loop=$td_counter;$loop < 4; $loop++){ echo "<td></td>"; } echo "</tr>"; } ?> EDIT: heh deadon arrival beat me to it Quote Link to comment Share on other sites More sharing options...
avo Posted March 7, 2008 Author Share Posted March 7, 2008 Thank you both Appriciated works a treat.. Quote Link to comment Share on other sites More sharing options...
deadonarrival Posted March 7, 2008 Share Posted March 7, 2008 Most welcome, glad it worked Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.