'How to add comma separate a string and also add the word "and" just before the last item [duplicate]

I have a string which is concatenated together that needs to be comma separated. I also want to add the work "and" just before the last item.

?php
   $general = get_field('general');
   $language_inclusions = $general['language_inclusions'];
   

   foreach ($language_inclusions as $language) {
   echo $language['language']; 

   } ?>

This is my output

EnglishPortugueseChinese

expected result should be English, Portuguese **and** Chinese

php


Solution 1:[1]

There are implode method available for join two values of array.

function join_string($array){
    #Filter array for remove null value from array
    $array = array_filter($array);

    #remove the last value and store it in variable
    $last_value = array_pop($array);

    return implode(', ',$array)." and ".$last_value;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1