Comma separated tax terms, with “and” before last item [duplicate]

This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related.

$locations = get_the_terms($post->ID, 'location');
$locations = array_values($locations);

$total_locations = count($locations); // the total start from 1

for($i = 0; $i < $total_locations; $i++) {

    echo $locations[$i]; // echo the location

    if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0
        echo ', '; // echo comma
    } elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions 
        echo ' and '; // echo and
    }
}