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

时间:2011-01-07 15:46:20

标签: 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 ,

3 个答案:

答案 0 :(得分:7)

<?php
$sentence = implode(', ', $words);
?>

答案 1 :(得分:5)

使用implode

$final_sentence = implode(", ", $words);

答案 2 :(得分:4)

$final_sentence = implode(', ',$words)