优化PHP代码(用逗号连接单词,删除最后一个逗号)

Dot*_*Dot 1 php string

我几乎总是使用这种方法从数组中获取"Word1,Word2,Word3"('Word1','Word2','Word3')

它是最短或可接受的方法吗?更好的解决方案?

$sentence = '';
foreach ($words as $word) {
    $sentence .= $word . ", ";
}
$final_sentence = substr($sentence, 0, -2);

echo $final_sentence; //outputs contents of $words array separated by ,
Run Code Online (Sandbox Code Playgroud)

the*_*dom 7

<?php
$sentence = implode(', ', $words);
?>
Run Code Online (Sandbox Code Playgroud)


Dom*_*ger 5

用途implode:

$final_sentence = implode(", ", $words);
Run Code Online (Sandbox Code Playgroud)