Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add different class to even and odd divs

Tags:

I have a block of PHP code that looks like this:

$flag = false;
if (empty($links))
{
    echo '<h1>You have no uploaded images</h1><br />';
}

foreach ($links as $link)
{   
    $extension  = substr($link, -3);
    $image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);  

    ($delete_submit) ? deleteImage('.' . $image_name, $link) : '';

    echo '<div>';
        echo '<table>';

        echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';

        echo '<tr><td><span class="default">Direct:</span>&nbsp;';
        echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />'; 
        echo '</td></tr>';

        echo ($flag) ? '<hr /><br>' : '';

        echo '</table>';
        echo '<br>';
    echo '</div>';

    $flag = true;
}

I want the <div> to include a different class based on if it is even or odd. If it is even, it gets X class, if it's odd it gets Y class.

How do I do this in my case? I'm totally clueless and I don't know how to start!

like image 331
aborted Avatar asked Dec 16 '11 21:12

aborted


2 Answers

Initialise a variable $count=0; before the loop. Then place the following in the loop: ++$count%2?"odd":"even".

$count = 0;
foreach ($links as $link)
{   
    $extension  = substr($link, -3);
    $image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);  

    ($delete_submit) ? deleteImage('.' . $image_name, $link) : '';

    echo '<div class="' . (++$count%2 ? "odd" : "even") . '">';
like image 165
Rob W Avatar answered Nov 17 '22 05:11

Rob W


[...]
$i++;
echo '<div class="'.($i%2 ? 'odd':'even').'>';
[...]
like image 37
konsolenfreddy Avatar answered Nov 17 '22 05:11

konsolenfreddy