How can the issue of adding a delimiter to all elements except the last one be efficiently resolved within a foreach loop in PHP?

When iterating over an array using a foreach loop in PHP, it can be challenging to add a delimiter to all elements except the last one. One efficient way to solve this issue is to store all elements in a temporary array and then use implode() function to join them with the delimiter. This way, the delimiter is only added between elements, not at the beginning or end.

$items = ["apple", "banana", "cherry", "date"];
$finalOutput = '';

$tempArray = [];
foreach ($items as $item) {
    $tempArray[] = $item;
}

$finalOutput = implode(', ', $tempArray);

echo $finalOutput;