Wal-Wal-2 Posted January 12, 2020 Share Posted January 12, 2020 (edited) I have an array of data in which I want to display in a table with the first row of data to not be formatted. In the second row of data, I want it formatted with the CSS class of "success". When I run this code, I do not get any formatting of any rows in the table. I have tried various different options without success. Any help would be greatly appreciated. <?php $counter = 0; while($row = mysql_fetch_array($query)) { if($counter % 2 == 0) { //output data from each row of data with no class of "success" echo "<tr class='text-left'>"; if (empty($row[endDate])) { echo "<td>".$row[startDate]."</td>"; /* only one date */ } else { echo "<td>".$row[startDate].'-'.$row[endDate]."</td>"; /*date range */ } echo "<td>".$row[rideName]."</td>"; echo "<td>".$row[rideDesc]."</td>"; echo "<td>".$row[location]."</td>"; echo "<td><a href='".$row[link]."'>".$row[source]."</a></th>"; echo "</tr>"; $counter++; } else { //output data from each row echo "<tr class='text-left success'>"; if (empty($row[endDate])) { echo "<td>".$row[startDate]."</td>"; } else { echo "<td>".$row[startDate].'-'.$row[endDate]."</td>"; } echo "<td>".$row[rideName]."</td>"; echo "<td>".$row[rideDesc]."</td>"; echo "<td>".$row[location]."</td>"; echo "<td><a href='".$row[link]."'>".$row[source]."</a></th>"; echo "</tr>"; $counter++; } /* end if else */ } /* end while */ ?> Edited January 12, 2020 by Wal-Wal-2 Copied wrong set of code Quote Link to comment https://forums.phpfreaks.com/topic/309826-loop-through-array-with-incremental-for-striped-table/ Share on other sites More sharing options...
Barand Posted January 12, 2020 Share Posted January 12, 2020 Try incrementing the counter at the end of the loop. Also no need for all the duplicate code. All you need is to set a variable $suc = $counter % 2 == 1 ? 'success' : ''; E.G. $counter = 0; foreach ($res as $row) { $suc = $counter % 2 == 1 ? 'success' : ''; $tdata .= "<tr class='$suc'> <td>{$row['firstname']}</td> <td>{$row['lastname']}</td> </tr>"; $counter++; } then <table> <?=$tdata?> </table> Quote Link to comment https://forums.phpfreaks.com/topic/309826-loop-through-array-with-incremental-for-striped-table/#findComment-1573374 Share on other sites More sharing options...
requinix Posted January 12, 2020 Share Posted January 12, 2020 FYI, this can be (and should be) handled entirely with CSS using nth-child(), not(), and first-child. 1 Quote Link to comment https://forums.phpfreaks.com/topic/309826-loop-through-array-with-incremental-for-striped-table/#findComment-1573382 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.