开发者

Optimize PHP code (concatenating words with a comma, removing last comma)

开发者 https://www.devze.com 2023-02-02 20:27 出处:网络
I\'ve used this method almost always to get \"Word1, Word2, Word3\" from an array(\'Word1\', \'Word2\', \'Word3\')

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消