Created
July 22, 2014 19:54
-
-
Save pat-eason/04a1023e3c277644b523 to your computer and use it in GitHub Desktop.
Ruby's Cycle function in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cycle($first_value, $values = '*') { | |
static $count = array(); | |
$values = func_get_args(); | |
$name = 'default'; | |
$last_item = end($values); | |
if( substr($last_item, 0, 1) === ':' ) { | |
$name = substr($last_item, 1); | |
array_pop($values); | |
} | |
if( !isset($count[$name]) ) | |
$count[$name] = 0; | |
$index = $count[$name] % count($values); | |
$count[$name]++; | |
return $values[$index]; | |
} | |
/* | |
Sample usage: | |
for($x=0; $x<=5; $x++){ | |
echo cycle('one, ','two, ','three, '); | |
} | |
Output: | |
one, two, three, one, two | |
I mostly use this for ping-ponging markup classes instead of using JS for them. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment