1

I have a smiliar loop:

$names = "
[$name , $surname]
";

echo "$names";

The result:

[Mario,Rossi]
[Aberto,rossi]
[Giovanni,Rossi]

i would this output:

[Mario,Rossi],
[Aberto,rossi],
[Giovanni,Rossi]

Without , in the last result
* I can't know the number of results in the loop

5
  • 1
    Why don't you know the loop count? Commented Apr 4, 2012 at 20:43
  • Could you show all your code, please? Commented Apr 4, 2012 at 20:44
  • @lonesomeday - suppose that there is more code to come :) I don't think so.... Commented Apr 4, 2012 at 20:45
  • 1
    @MichalPlško Well, that code couldn't produce that output, so clearly there's something else... Commented Apr 4, 2012 at 20:46
  • @binarious: Why would you need to know the loop count? Commented Apr 4, 2012 at 21:07

2 Answers 2

3
$names[] = "
[$name , $surname]
";

$comma_sep = implode(",", $names);

echo "<pre>{$comma_sep}</pre>";

The data should be pre-formatted with <pre> tags if you want to use your line breaks like that.

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

4 Comments

I would remove the pre tags. Although php is normally used as a server side language it can be used through the command line where the newlines have significance and the pre tags would be incorrect. PHP server side can also be used to return a file other than html. For example it can be used to return a plain text file.
@MitMaro I used his variable design and he said he wanted an output with line breaks (without OP using \n). I wouldn't do it like that, but I don't know how the OP intends to use it, either.
He didn't use \n he used a literal line break in his string.
@Truth Don't you love it when vagueness is matched with expected mind reading? :)
2

Using a simple array implosion will do the trick here:

$names[] = "[$name, $surname]";
echo implode(",\n", $names);

Comments

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.