1

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
  • What does $require contain? Where are the words? Commented Jan 15, 2011 at 22:50

3 Answers 3

5
$require_1 = implode(', ', $require);

Will this do? It places a comma and a space after each item

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

1 Comment

Thanks, however it treats '&' as a word. How can I stop it placing a comma after &? EDIT: It also puts a comma after any space. So say I have Test (testing) it equals to Test, (testing).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.