PHP Foreach and Reference Variables

Here’s a crazy gotcha.  I was playing with references when I realized that I was getting the wrong values.

Here’re the values that I used:
$valuearray = array(‘%CTRL%’, ‘%2%’);

Here’s my original loop:

foreach($valuearray as $val)
(
    $params[] = &$val;
)

 

And here’s what the print_r($params) gave me.

Array
(
    [0] => %2%
    [1] => %2%
)

Do you see the problem yet?

In a nutshell, I was trying to load references of each element in $valuearray into $params.  It wasn’t working too well because I was shoving the reference of $val itself into $params.  Whatever $val last points at is what’s going to show up for all elements in the array.  Interesting!  But ultimately not what I was aiming for.

http://www.php.net/manual/en/control-structures.foreach.php

The above link had part of the solution.  The next step of the debugging process would be this loop (I’ve highlighted the change in cyan):

foreach($valuearray as &$val)
(
    $params[] = $val;
)

And here’s what the print_r($params) gave me.

Array
(
    [0] => %CTRL%
    [1] => %2%
)

That’s correct.  But we’re not out of the woods yet.  If you’re trying to shove this into a mysql query that needs references, it should give you an error that a value was received when it was expecting a reference.

Here’s the final iteration (I’ve highlighted the change in cyan):

foreach($valuearray as &$val)
(
    $params[] = &$val;
)

And now I’ve fulfilled my original goal, load references to an array’s elements into another array.

Leave a Reply

Your email address will not be published. Required fields are marked *