I’m having a strange problem with PHP’s reference(&).
Let’s say I have a form that looks like:
<form name="form1" id="form1" method="post">
Name: <input type="text" name="name" /><br />
Email: <input type="text" name="email" /><br />
Location: <input type="text" name="location" /><br />
Phone Number: <input type="text" name="phonenumber" /><br />
</form>
And then I submit that form to another PHP handler. And the handler does this:
foreach($_POST as $name => &$value)
{
//more code here
}
echo $_POST['phonenumber']; //Returns value of $_POST['location'] for some reason
Can someone explain to me why the value of phone number would be the value of whatever location is? Even if there is no code inside of the foreach it still does this.
EDIT:
For those of you wondering what is going inside the foreach, or why I’m even doing this, it’s because it’s a clean way to escape all the data submitted to the handler, instead of doing it one variable at a time manually, especially when you have dynamic input coming in. So like this:
foreach($_POST as $name => &$value)
{
$value = preg_replace( "/[<>#$%]/", "", $value);
$value = preg_replace('/\s\s+/', ' ', $value);
}
It works beautifully except for the problem I stated above.
Are you perhaps iterating it twice, once with a reference and once without? It makes a big difference:
And here’s a demo. The fix is to unset
$valuebetween the loops: