简体   繁体   中英

Why won't this PHP iteration work?

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!

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

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM