开发者

foreach with cycle/alternate options

I am looking for a fastest(performance) way to cycle/alternative 2 values inside of a foreach loop. Exactly the same as the smarty works: http://www.smarty.net/d开发者_运维知识库ocsv2/en/language.function.cycle


Cycling is easy with the modulo operator.

$cycle = $iteration % $cycles;

If $cycles is 2, for instance, then $cycle will contain 0 and 1 alternating as $iteration increases.

Then if you need specific values for these cycles, use a look-up table:

$lookup = array('value1', 'value2');
$value = $lookup[$cycle];

The foreach loop does not keep track of iterations, though; You'd want to use a for loop for that instead. Or increment an iteration variable yourself.


$cycle = array('value1', 'value2');
$i = 0;

foreach (...) {
    $cycle[$i] // current cycle value
    ...
    $i = 1 - $i; // here be cycling
}

P.S. And don't think you should be very concerned about performance in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜