php loop output

Go To StackoverFlow.com

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

2012-04-04 20:40
by Geme
Why don't you know the loop count - binarious 2012-04-04 20:43
Could you show all your code, please - lonesomeday 2012-04-04 20:44
@lonesomeday - suppose that there is more code to come :) I don't think so... - Michal 2012-04-04 20:45
@MichalPlško Well, that code couldn't produce that output, so clearly there's something else.. - lonesomeday 2012-04-04 20:46
@binarious: Why would you need to know the loop count - Madara Uchiha 2012-04-04 21:07


2

Using a simple array implosion will do the trick here:

$names[] = "[$name, $surname]";
echo implode(",\n", $names);
2012-04-04 20:48
by Madara Uchiha
Thanks !! With this i solve the proble - Geme 2012-04-04 21:02


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.

2012-04-04 20:46
by Blake
Not sure why this got downvoted.. - Madara Uchiha 2012-04-04 20:47
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 2012-04-04 20:56
@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 - Blake 2012-04-04 20:58
He didn't use \n he used a literal line break in his string - Madara Uchiha 2012-04-04 21:02
@Truth Don't you love it when vagueness is matched with expected mind reading? : - Blake 2012-04-04 21:05
Ads