How can the size of an array be compared within a loop to identify the last iteration in PHP?

To identify the last iteration in a loop in PHP, you can compare the current iteration index with the size of the array. If the current index is equal to the size of the array minus one, then it is the last iteration. This can be achieved by using the count() function to get the size of the array and decrementing it by one to get the last index.

$array = [1, 2, 3, 4, 5];
$arraySize = count($array);

foreach ($array as $key => $value) {
    if ($key == $arraySize - 1) {
        echo "Last iteration reached!";
    } else {
        echo "Not the last iteration.";
    }
}