How can the implode function be used to concatenate elements in an array without adding a comma after the last item?

When using the implode function in PHP to concatenate elements in an array, by default, it adds a comma after each item, including the last one. To avoid adding a comma after the last item, you can use a combination of implode and array_slice functions. By using array_slice to exclude the last element before imploding the array, you can achieve the desired result of concatenating elements without a comma after the last item.

$array = ["apple", "banana", "orange"];
$lastItem = array_slice($array, -1);
$firstItems = array_slice($array, 0, -1);

$concatenatedString = implode(", ", $firstItems) . (count($array) > 1 ? " and " : "") . implode("", $lastItem);

echo $concatenatedString;