Alex
Alex

Reputation: 31

Add Class to a div with PHP foreach

Consider this array of classes:

$array =['blue', 'gren', 'red', 'orange', 'yellow', 'pink'];

I need for each each div to have a class:

foreach ($array as $div) {
    echo '<div class="">'.$div.'</div>';
}

Example of what I need:

<div class="first">blue</div>
<div class="second">gren</div>
<div class="last">red</div>

<div class="first">orange</div>
<div class="second">yellow</div>
<div class="last">pink</div>

Suppose I have 100 records in an array.

first
second
last

first
second
last

first
second
last

first
second
last

Etc.

Upvotes: 0

Views: 1171

Answers (3)

Guillaume Boudreau
Guillaume Boudreau

Reputation: 2877

You can simply use the array index to check if it's a first, second or last div, using the % operator. For example:

foreach ($array as $i => $div) {
    if ($i % 3 == 0) {
        $class = 'first';
    } elseif ($i % 3 == 1) {
        $class = 'second';
    } else {
        $class = 'last';
    }
    echo "<div class='$class'>$div</div>";
}

Upvotes: 0

Alexander Topalo
Alexander Topalo

Reputation: 36

foreach ($array as $n => $div) {
    if ($n % 3 == 0) $pos = 'first';
    elseif ($n % 3 == 1) $pos = 'second';
    else $pos = 'last';

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

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30360

If I understand your requirements correctly, this should be achievable via the following code. Consider tracking the current index ($i) of your iteration to determine the class to apply to a div. Notice I use the modulo operator % with a switch block to decide which class to use per iteration:

$i = 0;

foreach ($array as $div) {

    $i++;

    $class = "";
    switch ($i % 3) {
        case 0:
            $class = "first";
            break;
        case 1:
            $class = "second";
            break;
        case 2:
            $class = "third";
            break;
    }

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

Upvotes: 0

Related Questions