1

I have four divs in one page which are styled so that it has four alternating colours. And the even div i.e. 2nd and 4th have an extra class name 'r' like this.

<div class="x-1 liner"><div>
<div class="x-2 liner r"><div>
<div class="x-3 liner"><div>
<div class="x-4 liner r"><div>

The results are pulled from the database, I can use the modulus operator (%) to assign alternating colours for two rows as shown in here but how can I do this for four rows and also add 'r' to the even divs?

1
  • Use %2 for the r values and %4 for the colours. Commented Apr 26, 2015 at 0:34

1 Answer 1

3

As kojow7 says you can use % 2 and % 4, see this code:

<?php

for($i = 1; $i <= 4; $i++) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'><div>\n"; 
}   

?>

Output:

div class='x-1 liner'><div>
div class='x-2 liner r'><div>
div class='x-3 liner'><div>
div class='x-4 liner r color'><div>

EDIT: With a foreach should be like this, but I don't know what values have $data

<?php

$i = 1;

foreach($data as $row) {
  echo "div class='x-$i liner";
  if($i % 2 == 0) echo ' r';
  if($i % 4 == 0) echo ' color';
  echo "'><div>\n"; 
  $i++;
}   

?>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for that, how can use this inside a foreach loop like this: foreach($data as $row) { } if I place it inside I get the results four times. What am I doing wrong?
@AbuNooh I edit my answer, but I don't know the values in your $data var
That's it done, big thanks. Also found I could just increment a number without the loop but this is perfect.
@AbuNooh you're welcome and god luck in your work ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.