How can you ensure that the last iteration of a loop in PHP includes both the remaining values from the array and the initial values?

When iterating over an array in PHP, the last iteration may not include all the remaining values from the array if the loop condition is based on the array's length. To ensure that the last iteration includes both the remaining values and the initial values, you can use a flag to track whether it is the last iteration. If it is the last iteration, you can loop through the remaining values in the array.

<?php
$array = [1, 2, 3, 4, 5];
$lastIteration = false;

foreach($array as $key => $value){
    if($lastIteration){
        echo $value . " ";
    }
    
    if($key == count($array) - 1){
        $lastIteration = true;
    }
    
    echo $value . " ";
}
?>