You’ll need to do something else
$location_count = count($locations);
$counter = 0;
foreach ($locations as $location) {
$counter ++;
if ($counter > 1) {
if ($counter < $location_count) {
echo ', ';
} else {
echo ' and ';
}
}
// rest of your code here
}