Welcome Guest, Not a member yet? Register   Sign In
foreach alternate like table
#2

[eluser]danmontgomery[/eluser]
You need to keep a counter, and check if that counter is even or odd. You can do this with modular division.

Code:
$count = 0;
foreach($list as $item) {
    if($count % 2) {
        $class = 'a';
    } else {
        $class = 'b';
    }

    echo '<div class="'.$class.'">code</div>';

    $count++;
}

You can shorten this with the ternary operator:

Code:
$count = 0;
foreach($list as $item) {
    echo '<div class="'.($count++%2?'a':'b').'">code</div>';
}

You can also use the alternator() function in the string helper: http://ellislab.com/codeigniter/user-gui...elper.html

Code:
for ($i = 0; $i < 10; $i++)
{
    echo alternator('string one', 'string two');
}


Messages In This Thread
foreach alternate like table - by El Forum - 01-12-2011, 04:07 PM
foreach alternate like table - by El Forum - 01-12-2011, 04:11 PM
foreach alternate like table - by El Forum - 01-12-2011, 04:13 PM
foreach alternate like table - by El Forum - 01-12-2011, 04:17 PM
foreach alternate like table - by El Forum - 01-12-2011, 07:43 PM
foreach alternate like table - by El Forum - 01-13-2011, 07:51 AM
foreach alternate like table - by El Forum - 01-13-2011, 01:09 PM



Theme © iAndrew 2016 - Forum software by © MyBB