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