问题
I have this for loop:
for($i=0; $i < $N; $i++)
$require_1 .= $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.
回答1:
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
回答2:
$require_1 = implode(', ', $require);
Will this do? It places a comma and a space after each item
回答3:
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.
来源:https://stackoverflow.com/questions/4702563/php-for-loop-adding-commas