In what ways can you optimize the code provided to correctly display the separator only until the last page in PHP pagination?

To optimize the code to correctly display the separator only until the last page in PHP pagination, you can modify the logic that determines when to display the separator. One way to achieve this is by checking if the current page is the last page and only displaying the separator for pages before it.

<?php
$totalPages = 10;
$currentPage = 5;
$separator = ' | ';

for ($i = 1; $i <= $totalPages; $i++) {
    if ($i == $totalPages) {
        echo $i;
    } else {
        echo $i . $separator;
    }
}
?>