PrimitiveType

PHP: highlight alternate rows in HTML output

The examples below assume we want to display a list of items on an HTML page and attach a CSS class called "highlight" only to every other item:

<?php // If we know a collection's row numbers are sequential, we can check for even row numbers using // the modulo operator % and highlight only even (or odd) rows $items = array(1 => 'mug', 2 => 'toaster', 3 => 'kettle', 4 => 'plate', 5 => 'spoon'); foreach ($items as $index => $item) { echo '<span class="item' . ($index % 2 == 0 ? ' highlight' : '') . '">' . $item . '</span><br />' . PHP_EOL; } // When we can't rely on row numbers being sequential, we can create a boolean variable and flip its // value (by assigning it to a negated version of itself with !) on every iteration of the loop $items = array(3 => 'mug', 7 => 'toaster', 2 => 'kettle', 8 => 'plate', 9 => 'spoon'); $shouldHighlight = false; foreach ($items as $item) { echo '<span class="item' . ($shouldHighlight ? ' highlight' : '') . '">' . $item . '</span><br />' . PHP_EOL; $shouldHighlight = !$shouldHighlight; } /* Both of the examples above print the following: <span class="item">mug</span><br /> <span class="item highlight">toaster</span><br /> <span class="item">kettle</span><br /> <span class="item highlight">plate</span><br /> <span class="item">spoon</span><br /> */