php – Displaying a table with alternating three row colors

Question:

The table represents the characteristics of the product. There is a heading of a group of characteristics and the characteristics themselves. It is necessary to display an array of settings in the form of a table in such a way that the color alternation always starts with one color. The odd and even variant, I know how to do it:

foreach($specs_item_full AS $key => $value){
  $i++;
  if($i $i%2 == 0){
    echo "<tr style='background-color: #eeeeee'>
                <td class='spec_title'>
                    $key
                </td>
                <td class='spec_details'>
                    $value
                </td>
            </tr>
            ";
  } else {
    echo "<tr style='background-color: #e2e2e2'>
                <td class='spec_title'>
                    $key
                </td>
                <td class='spec_details'>
                    $value
                </td>
            </tr>
            ";
  }
}

But I don’t understand how to display the title yet. Moreover, in the variant that is indicated above, the alternation does not start with one color – if there is an even number of elements in the array, then it starts with one color, if it is odd, with another. If I ended up with different colors, it’s clear, but here it’s not clear. The array key is the name of the characteristic in Cyrillic, the value is the characteristic value itself. The title comes with an empty value.

Answer:

You can store the value of the current section in a separate variable, for example $ key_curr. Compare this value with the previous value at each iteration, if they coincide, display the characteristics alternately.

<?php
$key_curr = null;
$i = 0;
foreach($specs_item_full AS $key => $value){

  if($key == $key_curr) {
    $i++;

    if($i % 2) $color = "#eeeeee";
    else $color = "#e2e2e2";

    echo "<tr style='background-color: {$color}'>
                <td class='spec_title'>
                    $key
                </td>
                <td class='spec_details'>
                    $value
                </td>
            </tr>
            ";
  } else {
    $key_curr = $key;
    echo "<tr style='background-color: #ffffff'>
                <td class='spec_title' colspan='2'>
                    $key
                </td>
            </tr>
            ";
  }

}

If in the next section you need to continue alternating the previous one – just use the previous value of the counter $ i, if you need to start alternating colors from some starting color, zero the value of $ i in the else-block (the first option is given above).

Scroll to Top