Reputation: 2176
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
Upvotes: 1
Views: 2432
Reputation: 26312
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;
?>
Upvotes: 1
Reputation: 1518
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 } ?>
Upvotes: 0
Reputation: 298096
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 } ?>
Upvotes: 2
Reputation: 5742
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 } ?>
Upvotes: 0
Reputation: 2863
If you want to retain the same structure, you could nest ternaries.
echo (++$count%3==0 ? "3" : ($count%3==1 ? "3+1" : "3+2"))
Upvotes: 1
Reputation: 2713
The best way switching multiple css is by using
Control Structure Switch Statements
Upvotes: 0