What does this PHP foreach loop do? (Something to do with creating references to each element in an array?)

StackOverflow https://stackoverflow.com/questions/19871619

Question

Recently, I was trying to create a copy of a PHP array, except that instead of the copy of the array containing values, I wanted the copy to contain references to values.
My main motivation for this was to use the call_user_func_array function in conjunction with the mysqli_stmt_bind_param and mysqli_stmt_bind_result functions to create a wrapper function for handling prepared statements.

While trying to figure out how to do this, I came across the following code:

$arr = array(1, 2, 3, 4); // The array to make a copy of with references
$ref_arr = array();       // The new array that will contain the references

foreach ($arr as $key => &$val) {
  $ref_arr[$key] = &$val;
}

The above code does in fact give me what I want by creating a second array that's identical to the first except that the elements in the array are references to values instead of values themselves, however, I don't understand how it works.

I understand what the ampersand (&) does in PHP, but I don't understand why both instances of $val in the foreach loop have to be referenced as &$val.

If anyone could please explain what exactly is happening in the foreach loop above, I would be very appreciative.
Thanks a lot.

Was it helpful?

Solution

The first instance has to be a reference. Otherwise you would only get a local copy. Consider this code:

$arr = array(1, 2, 3, 4); 
foreach ($arr as $val)
    $val = 5;
print_r($arr);

This code would still print 1,2,3,4 as you are not altering the values in the array, but a copy.

The same logic applies for the second instance. Without &, it would only assign the current value of the element.

OTHER TIPS

mysqli_stmt_bind_param() requires values to be passed by reference. So all that function does is create an array that references values in the original array. That makes mysqli_stmt_bind_param happy. It's kinda silly but it's what we have to do to call call_user_func_array() with mysqli_stmt_bind_param().

Ref: see the manual for mysqli_stmt_bind_param()

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top