PHP Playground: Cycle

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s