How can PHP developers optimize the code to display a "Read More" link after a set number of news items without duplicating the link for each item displayed?
To display a "Read More" link after a set number of news items without duplicating the link for each item displayed, you can use a counter variable to keep track of the number of items displayed. Once the counter reaches the set number, display the "Read More" link. This way, the link will only appear once after the specified number of news items.
<?php
$newsItems = array("News item 1", "News item 2", "News item 3", "News item 4", "News item 5");
$counter = 0;
foreach ($newsItems as $item) {
echo $item . "<br>";
$counter++;
if ($counter == 3) {
echo "<a href='#'>Read More</a><br>";
}
}
?>