PHP for loop adding commas

南楼画角 提交于 2021-02-10 21:21:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!