1

We've been switching between an odd/even classes during a foreach loop like this:

<?php
  $count = 0;
  foreach ($pages as $page) { ?>

   <div class="row <php echo (++$count%2 ? "odd" : "even") ?>">
     ...page_list or product_list output
   </div>

<php } ?>

But how would we switch between 3 or more css classes?

Any pointers in the right direction would be much appreciated.

Cheers

Ben

6 Answers 6

2

Put them into an array and use the modulo operator:

<?php
  $count = 0;
  $classes = array('one', 'two', 'three');

  for ($i = 0; $i < 10; $i++) {
    $count = ++$count % count($classes);
    $class = $classes[$count];
  ?>

   <div class="row <?php echo $class ?>">
     ...
   </div>

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

Comments

1

If you want to retain the same structure, you could nest ternaries.

echo (++$count%3==0 ? "3" : ($count%3==1 ? "3+1" : "3+2"))

Comments

1

if the array key pair is numeric, you could just use a foreach loop with a key => value output and evaluate the key with the numbulus operator. then use the result in a switch statement.

if the array keys are not numeric you could set a variable before the foreach loop and increment it with every itteration and check for its value..

<?php
$pages = Array('page1', 'page2', 'page3');

foreach ($pages as $key => $page) :

  switch ( $key % 3 ) { (3 is the number of available cases)
    case 0:
      $class = 'class1';
      //…
      break;
    case 1:
       $class = 'class2 foo';
       //…
      break;
    case 2:
      $class = 'bar';
      //…
      break;
  endswitch;

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

endforeach;
?>

Comments

0

If else statements can be used and make sure to change the mod number.

Try this:

        <div class="row 
    <php
        ++$count;
        if($count % 3 == 0)
        {
            echo "style2";
        }
        else if($count % 3 == 1)
        {
            echo "style2";
        }
        else
        {
            echo "style3";
        }
    ?>
    ">
    ...page_list or product_list output
    </div>

<php } ?>

Comments

0

The best way switching multiple css is by using

Control Structure Switch Statements

Comments

0

having class1, class2 and class3

<?php
  $count = 0;
  foreach ($pages as $page) {
  $count = $count == 3 ? 0 : $count++;
?>
   <div class="row <?php echo "class".$count ?>">
     ...page_list or product_list output
   </div>
<?php } ?>

Comments

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.