Optimize PHP code (concatenating words with a comma, removing last comma)
I've used this method almost always to get "Word1, Word2, Word3" from an array('Word1', 'Word2', 'Word3')
Is it the shortest or acceptable method? Any better solution?
$sentence = '开发者_如何转开发';
foreach ($words as $word) {
$sentence .= $word . ", ";
}
$final_sentence = substr($sentence, 0, -2);
echo $final_sentence; //outputs contents of $words array separated by ,
<?php
$sentence = implode(', ', $words);
?>
Use implode
:
$final_sentence = implode(", ", $words);
$final_sentence = implode(', ',$words)
精彩评论