Skip to content

Instantly share code, notes, and snippets.

@BaylorRae
Created August 31, 2012 21:48
Show Gist options
  • Save BaylorRae/3559617 to your computer and use it in GitHub Desktop.
Save BaylorRae/3559617 to your computer and use it in GitHub Desktop.
<?php for( $i = 0; $i < 9; $i++ ) : ?>
<p><?php echo cycle('one', 'two', 'three') ?></p>
<?php endfor; ?>
<?php for( $i = 0; $i < 9; $i++ ) : ?>
<p class="<?php echo cycle('odd', 'even') ?>">
<?php echo cycle('one', 'two', 'three', ':counter') ?>
</p>
<?php endfor; ?>
<?php
/**
* Cycles through each argument added
* Based on Rails `cycle` method
*
* if last argument begins with ":"
* then it will change the namespace
* (allows multiple cycle calls within a loop)
*
* @param mixed $values infinite amount can be added
* @return mixed
* @author Baylor Rae'
*/
function cycle($first_value, $values = '*') {
// keeps up with all counters
static $count = array();
// get all arguments passed
$values = func_get_args();
// set the default name to use
$name = 'default';
// check if last items begins with ":"
$last_item = end($values);
if( substr($last_item, 0, 1) === ':' ) {
// change the name to the new one
$name = substr($last_item, 1);
// remove the last item from the array
array_pop($values);
}
// make sure counter starts at zero for the name
if( !isset($count[$name]) )
$count[$name] = 0;
// get the current item for its index
$index = $count[$name] % count($values);
// update the count and return the value
$count[$name]++;
return $values[$index];
}
?>
<?php
$things = array('shoe', 'sox', 'sand', 'laptop', 'guitar', 'bag', 'legos', 'elephpant', 'stapler', 'binder', 'desk', 'chair');
foreach( $things as $thing ) :
?>
<div class="grid_4 <?php echo cycle('alpha', '', 'omega') ?>">
<?php echo $thing ?>
</div>
<?php if( cycle(false, false, true, ':use_clear_div') ) : ?>
<div class="clear">// clear div every three items</div>
<?php endif; ?>
<?php endforeach; ?>
@jCrip
Copy link

jCrip commented Sep 11, 2014

Hi, is there a way to reset the cycle function, to start over?

Thanks in advance!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment