PHP for loop adding commas
I have this for loop:
for($i=0; $i < $N; $i++)
$require_1 .开发者_C百科= $require[$i] . " ";
I would like it to place a comma on the end of the first word, if there's 2 words in the string. However if there's only 1 word in the string I want it left alone.
I understand I need to use an if statement, based on $i
. However I'm not sure how I do this.
$require_1 = implode(', ', $require);
Will this do? It places a comma and a space after each item
This is a trick I use a lot to make strings like that,
$require_1 = "";
for ($i = 0; $i < $N; $i++) {
if ($require_1 == '' || $require_1 == '&') {
$require_1 .= $require[$i];
}
else {
$require_1 .= ', '.$require[$i];
}
}
edit - added another condition for '&' char
for($i=0; $i < $N; $i++) {
$require[$i] = explode(' ', $require[$i]);
$require[$i] = implode(', ', $require[$i]);
$require_1 .= $require[$i] . " ";
}
this will break up each string, and add commas beteen each word.
精彩评论