tags:

views:

25

answers:

3

I have the following foreach

foreach( $array as $v )
{
    if( SOME LOGIC HERE ) $class = "first";
    if( SOME LOGIC HERE ) $class2 = "third";
        print '<span class="$class $class2">$v["name"]</span>';
} 

I want to set $class1 to be 'third' for every 1st, 4th, 7th, 10th (3n - 2) and $class2 to be set to 'third' for 3rd, 6th, 9th, 12th

A: 

Use the modulus operator

for ($i=0; $i<count($array); $i++)
    {
    if (($i-1)%3 == 0)
        $class = "first";
    else if ($i % 3 == 0)
        $class = "third";

    echo '<span class="'.$class.'">blablabla</span>
    }
nico
Won't work! Just tried it.. with array of 3 elements it gives the classes; third, first, first. Oh.. and a '; is missing after the echo
Phliplip
@Phliplip: Ok, I probably misread your question, I thought you were talking about element 1, not 1st element (PHP indices start at 0 not 1). Anyway you just need to use `$i%3`, `($i-1)%3`, and `($i-2)%3` to get each first, second and third element, then apply the class you need. (I'm sorry but it's not superclear from your question what exact output you want)
nico
FYI: Not my question :)
Phliplip
@Phliplip: oopsie! :)
nico
+2  A: 
foreach( $array as $k => $v ) 
{ 
    if (($k % 3) == 0) { $class = "first"; }
    elseif(($k % 3) == 2) { $class = "third"; }
    else { $class = "second"; }

    print '<span class="$class $class2">$v["name"]</span>'; 
}  
Mark Baker
This works! But what if the key is not a number?
Phliplip
If the key is not a number, then $k % 3 will cast $k to a numeric 0, so $k % 3 will always be 0 % 3 giving a result of 0.... but in most cases, people asking these questions are working with integer key values
Mark Baker
A: 
<?php
$n = 0;
foreach( $array as $v ) 
{ 
    $n++;
    switch($n) {
        case 1:
            $class = 'first';
            break;
        case 3:
            $class = 'third';
            $n = 0;
            break;
        default:
            $class = '';
            break;
    }
    print '<span class="' . $class . '">' . $v['name'] . '</span>'; 
}
?>

Edit: Updated the code, the print should go inside the loop :) and cleaned up the code.

Phliplip
Btw. if you don't actually need $class AND $class2 you could just rename $class2 to $class and remove $class2 from the span
Phliplip