tags:

views:

21

answers:

2

I want to change the classes on every third output from a query:

    <?php
$style_classes = array('box','box','box no_right_margin');
$style_index = 0;
?>

I set this on the div:

<div <?php $k = $style_index%4; echo "class=$style_classes[$k]"; $style_index++; ?>>

On the third div I want the class to look like this:

<div class="box no_right_margin">

Right now it looks like:

 <div class="box" no_right_margin>
A: 

You need to enclose the class names in quotes. Your script is actually outputting class=box no_right_margin. (I think the example you gave as the current output is not what the script is sending, but the view of the DOM from something like Firebug, which is showing the browser as only seeing the first class in the list)

So you could do this:

<div class="<?php $k = $style_index%4; echo $style_classes[$k]; $style_index++; ?>">

or even

<div class="<?php echo $style_classes[$style_index++ % 4]; ?>">
Tom Haigh
A: 

You should use %3 instead of %4, so you actually get indexes 0, 1 and 2.
And you need correct quotes in your HTML output:

<?php   echo '<div class="' . $style_classes[$k++ % 3] . '">';   ?>

Else your browser (Safari?) would probably correct it with a " at the wrong place, as shown in your example. Btw, it's better style to use hyphens for CSS class names, not underscores (unlike IDs).

mario