Here’s a freebie that can be used immediately without any supporting libraries. This will be available in the near future in my opensource php framework: tgsf It’s released under the GPLv3.
Use it like this:
<?php for ( $ix = 0; $ix < 10; $ix++ ) { echo alternateNs( 'one', '1','2' ) . PHP_EOL; echo alternateNs( 'two', 'a','b' ) . PHP_EOL; }
And here is the function:
<?php /** * Alternate with a namespace * The first argument is a namespace to enable multiple calls in a single loop * Call with a set of arguments and this function will return them based on a modulus of the quantity of invocations * in other words, each time you call this function it will return the next item in the list of parameters. * to reset, call with a namespace and different arguments */ function alternateNs() { $args = func_get_args(); $ns = array_shift( $args ); $argCnt = count($args); if ( empty( $ns ) ) { throw new Exception( 'alternateNs called without a namespace' ); } static $cache = array(); if ( empty( $cache[$ns] ) ) { $cache[$ns]['current'] = 0; $cache[$ns]['items'] = array(); } $items =& $cache[$ns]['items']; $current =& $cache[$ns]['current']; if ( ! ( $items === $args ) || $argCnt == 0 ) { $current = 0; $items = $args; } else { $current++; } return $argCnt>0?$args[$current % $argCnt]:''; }