How can one efficiently display multiple posts in a PHP script without causing an infinite loop or displaying duplicate content?

When displaying multiple posts in a PHP script, it's important to use a loop to iterate through each post and display its content. To avoid causing an infinite loop or displaying duplicate content, you should use a conditional statement to check if there are posts to display before entering the loop. Additionally, you can use an array to store the IDs of posts that have already been displayed to prevent duplicates.

<?php

// Assuming $posts is an array of post objects

$displayed_posts = array();

if (count($posts) > 0) {
    foreach ($posts as $post) {
        if (!in_array($post->id, $displayed_posts)) {
            // Display post content here
            echo "<h2>{$post->title}</h2>";
            echo "<p>{$post->content}</p>";

            $displayed_posts[] = $post->id;
        }
    }
}

?>