Scenario:
<?php $items = ['Item 1', 'Item 2', 'Item 3']; $index = 0 ; print "<ul>"; foreach( $items as $item ) { print '<li class="'. ( $index % 2 ? 'even' : 'odd') .'">' . $item . '</li>'; $index++; } print "</ul>"; ?>
You can cleanup the code more or use the array key to detect odd/even. For more than 2 class names or other cases where you want to do some cyclic operation there is no simple way. In Ruby they have cycle function that cycles through items. Twig & Smarty introduced cycle for class names.
With PHP5 closure and Functional programming you can build a reusable solution:
<?php /** * Cycle Function that rotates */ function cycle( $arr ) { return function() use(&$arr){ $arr[] = array_shift($arr); return end($arr); }; } $items = ['Item 1', 'Item 2', 'Item 3']; $cycle = cycle(['odd','even']); print "<ul>"; foreach( $items as $item ) { print '<li class="'. $cycle() .'">' . $item . '</li>'; } print "</ul>"; ?>
This time I am cycling through functions, maybe you could find its usage.
<?php function cycle( $arr ) { return function( $item ) use(&$arr){ $arr[] = array_shift($arr); $fn = end($arr); return $fn( $item ); }; } $items = ['Item 1', 'Item 2', 'Item 3']; $cycle = cycle([ function($item){ return strtoupper( $item ); }, function($item){ return ucfirst( $item ); } ]); print "<ul>"; foreach( $items as $item ) { print '<li>' . $cycle($item) . '</li>'; } print "</ul>"; ?>
If you have a better alternate plz share your thoughts.