How can PHP scripts be optimized and customized to efficiently handle the display of news articles with a paging function?

To optimize and customize PHP scripts for efficiently handling the display of news articles with a paging function, you can implement pagination logic to limit the number of articles displayed per page and provide navigation links for users to navigate through different pages of articles.

// Assuming $articles is an array containing all news articles
$articlesPerPage = 10;
$totalArticles = count($articles);
$totalPages = ceil($totalArticles / $articlesPerPage);

if (!isset($_GET['page']) || $_GET['page'] < 1 || $_GET['page'] > $totalPages) {
    $currentPage = 1;
} else {
    $currentPage = $_GET['page'];
}

$startIndex = ($currentPage - 1) * $articlesPerPage;
$displayedArticles = array_slice($articles, $startIndex, $articlesPerPage);

// Display articles
foreach ($displayedArticles as $article) {
    echo "<h2>{$article['title']}</h2>";
    echo "<p>{$article['content']}</p>";
}

// Display pagination links
for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='news.php?page={$i}'>{$i}</a> ";
}