Passing Arguments and Assigning Arrays in PHP
Arrays, a crucial data structure in PHP, are commonly passed to functions or assigned to variables. However, it's essential to understand how these operations affect their underlying references.
Arrays as Function Arguments
When an array is passed as an argument to a function, it is by default passed as a copy. This means the function operates on the copy itself, without modifying the original array. Suppose the function makes changes to the array; these changes won't reflect in the original array outside the function, unless the function is explicitly instructed to operate by reference.
function my_func($a) { $a[] = 30; } $arr = array(10, 20); my_func($arr); var_dump($arr); // Output: array(10, 20)
To pass the array by reference and allow the function to modify the original array, the function must be declared as:
function my_func(& $a) { $a[] = 30; }
Now, the changes made within the function will be reflected in the original array outside the function.
Assigning Arrays
When assigning an array to a new variable, the assignment creates a new copy of the array, unless the reference operator & is used. This means that the original array and the newly assigned variable are separate, and changes made to one will not affect the other.
$a = array(1, 2, 3); $b = $a; $b[] = 4; // $a still contains the original array (1, 2, 3)
To assign by reference, the reference operator & must be used:
$a = array(1, 2, 3); $b = & $a; $b[] = 4; // Both $a and $b now contain (1, 2, 3, 4)
The above is the detailed content of How Does PHP Handle Array Passing and Assignment by Reference?. For more information, please follow other related articles on the PHP Chinese website!