Montana
Montana

Reputation: 93

Coloring every second row in the foreach loop table

I have a problem, I need to color every second row in the table that is generated using the foreach loop. While in while and for is a simple banal, so in the foreach I completely do not know how to take it.

I put the code I was able to create, only one problem with it - it colors all the same lines.

<?php 
        $details = array_combine($_POST['detail'], $_POST['detail-description']);
        foreach($details as $key => $value) {
        $bg = ($i % 2 == 0) ? 'red' : 'yellow';
        ?>
            <tr style="background: <?php echo $bg; ?>;"><td style="padding: 3px 10px; text-align: right; border-right: 1px solid #dbdbdb;" width="50%">
            <?php echo $key ?>
            </td>
            <td style="padding: 3px 10px; text-align: left;" width="50%">
            <?php echo $value; ?>
            </td>
            </tr>
        <?php
        }
        ?>

Upvotes: 1

Views: 1370

Answers (1)

131
131

Reputation: 1385

The following code:

<?php 
$details = array(
    "test1"=>"tester1",
    "test2"=>"tester2",
    "test3"=>"tester3",
    "test4"=>"tester4",
    "test5"=>"tester5",
    "test6"=>"tester6",
    "test7"=>"tester7",
);
$i=0;
foreach($details as $key => $value) {
    $i++;
    $bg=($i%2==0?'red':'yellow');
    ?>
    <table>
        <tr style="background-color: <?php echo $bg; ?>;">
            <td style="padding: 3px 10px; text-align: right; border-right: 1px solid #dbdbdb;" width="50%">
                <?php echo $key ?>
            </td>
            <td style="padding: 3px 10px; text-align: left;" width="50%">
                <?php echo $value; ?>
            </td>
        </tr>
    </table>
    <?php
}
?>

Returns this:

enter image description here

You need table tags before you can apply background-color on tr tags.

Upvotes: 2

Related Questions