Not a bug Variable saves after foreach


Active member
Hello guys, possible it is market bug, but i don't know about it.

There is construction:
<xen:foreach loop="$conversations" value="$conversation">
// do something
After this code we can use $conversation in this template, this variable will contain last element of $conversations, i think it is incorrect. When i coded my plugin, i expected that $conversation is not available after foreach, i spent a lot of time to find error, why i put something in $viewParams['conversation'] and it replaces on last element of $conversations array

Chris D

XenForo developer
Staff member
The way it is now is the same way PHP and most languages would handle similar scenarios. We're not attempting to try and avoid any sort of variable pollution here, it's down to yourself to implement methods to avoid that in your own code.


Well-known member
php doesn't have block-level scoping, as such it doesn't actually matter if the foreach variable is defined inside or outside the block.

Languages like C/C++/C# do have block level scoping, and as such it impacts where the variable is defined.

C# explicitly changed the foreach variable to be defined inside the foreach scope to due to anonymous functions/lambdas causing unexpected behaviour when the variable is enclosed by the anonymous function.

Modern versions of Javascript also have block level scoping with the "let" keyword (vs the "var" keyword for function level scoping).