What are some best practices for efficiently changing background colors for different forum posts using PHP?

When displaying forum posts, it can be visually appealing to have alternating background colors for each post to improve readability. One way to efficiently achieve this is by using a conditional statement in PHP to check if the post index is even or odd, and then apply different background colors accordingly.

<?php
// Sample array of forum posts
$forum_posts = array(
    "Post 1",
    "Post 2",
    "Post 3",
    "Post 4",
    "Post 5"
);

// Loop through forum posts and display with alternating background colors
foreach($forum_posts as $index => $post) {
    if($index % 2 == 0) {
        echo '<div style="background-color: #f2f2f2;">' . $post . '</div>';
    } else {
        echo '<div style="background-color: #e6e6e6;">' . $post . '</div>';
    }
}
?>