[PHP] [TUT] How to make alternating table rows

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Ever wondered how people get those tables where each row has a different colour on them?

For example:
alternatingrows.gif

I just stole that off Google as an example.

Well, in this tutorial I am going to show you how to achieve that result. It's such an easy code and not very hard to remember.

PHP:
<?php
$table_data = array( "Mark" => "Eriksson",
                              "Steve" => "Jobs",
                              "Mark" => "Zuckerberg" ); //the data to put in a table, this will probably be retrieved from a database in your code.
 
$i = 0; //This is important, it tells the proceeding code what row class to use.
 
echo '<style>
.row-a { background-color: blue; }
.row-b { background-color: pink; }
</style>
 
<table>
    <thead>
        <th>First Name</th>
        <th>Last Name</th>
    </thead>
 
    <tbody>';
 
foreach ( $table_data as $firstname => $lastname )
{
    if ( $i == 0 ) //If $i is equal to 0, use 'row-a' and set $i to 1
    {
        $i++;
        $class = "a";
    }
    else // $i is not equal to 0, instead it is set to 1, so use class 'row-b' and set $i to 0
    {
        $i--;
        $class = "b";
    }
    echo '<tr class="row-"' . $class . '">
        <td>' . $firstname . '</td>
        <td>' . $lastname . '</td>
    </tr>';
}
 
echo '</tbody></table>';
?>

Now I'm not going to lie, I'm not even sure if that would work. I coded it in the post box on here so give it a try if you like.

Anyway, if the script above works, I hope it helps you in whatever you use it for.

- Mark.
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
I'm not the best at explaining things, so I hope it makes sense lol
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Thanks Christ!

By the way, MAKE SURE the if statement is inside the foreach statement.
 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,934
3,933
Why not do it like this?

PHP:
$class = ($i % 2 ? 'a' : 'b'); $i++;

Anyways, thanks for the share. ;)
 
Status
Not open for further replies.

Users who are viewing this thread

Top