My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

PHP – Odd/Even Table Rows

Alternate row colors (or zebra striping) is a great way to make long lists and tables easier to read. This technique is especially useful for large tables. In PHP, we can easily change the color of every other row of this table by using a ternary operator inside a while loop.

Consider the following code:

<table>
<?php
$class = 'class="red"'; // Set the initial background color.
$a = 1;
while ( $a<7 ) {
    $class = ($class=='class="red"' ? 'class="blue"' : 'class="white"'); // Switch the background color.
    echo '<tr ' . $class . '><td>list</td></tr>';
    $a++;
}
?>
</table>

Since we want to alternate the background color, this code will, upon each iteration of the loop, assign the opposite class to the $class. If $class is equal to white, then it will be assigned the value of blue and vice versa. For the first row fetched, $class is initially equal to white and will therefore be assigned blue, making a blue background.

Photo by Hammerin Man

1 comment

Have your say