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> '; 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!
Advertisement
Answer
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") . '">';