views:

188

answers:

4

I want to make the results of a foreach loop into a string variable I can use later all over (so I don't need to paste the foreach loop everywhere). I have this:

foreach($pairs as $d=>$m) {
$orderedpairs .= "[".$d."],[".$m."]"+"<br />";
}
echo $orderedpairs;

If I substitute the assignment operator with "echo", it works fine, so the loop is ok, I think it's just the variable assignment that's at issue. Thanks!

+12  A: 

You have a + in there for concatenation. You need .

Also, you should define $orderedpairs as an empty string before the loop.

Matt
Yup. This is the problem.
Andrew
It works when I zap that last "+". I haven't defined $orderedpairs, however. Can you expand on why I need to do that?
Alex Mcp
You don't have to but it's good practice.
Matt
A: 

Has $orderedpairs been declared as an empty string before the loop to instantiate and bring it into scope? Also should the final + actually be a . ?

Macros
+7  A: 

The plus sign is causing your concatenation to fail - change it to a .

Contrary to what others are saying, the scope of your variable is not the problem. You CAN declare them inside a loop and access them after it. PHP variables are not scoped like Java, C#, and other languages.

Rob Hruska
so your answer would be?
Peter Perháč
was just writing the same thing!
Paul Dixon
It works now with just zapping the "+". Can you explain a bit further why I need to define $orderedpairs outside the loop? It seems like the scope isn't an issue. Is it just a style thing?
Alex Mcp
PHP scoping is simpler than some other languages. Variables really only have a "global" or a "function" scope - if a variable is declared inside of a function it is accessible anytime after declaration within that function. It doesn't matter if it's inside an if statement, while loop, or any other block that would be considered a more narrow scope in a language like Java.
Rob Hruska
I wouldn't even say a style thing for $orderedpairs - I'd set it just before the start of the loop so I knew it was empty. Also, an undeclared variable would throw a warning.
Alister Bulman
+4  A: 

There's actually no need to concatenate with the operator in your case, you can just do:

$orderedpairs .= "[$d],[$m]<br />";

and PHP will replace the variables with their values.

John Rasch