Home > Backend Development > PHP Tutorial > How Does PHP Handle Array Passing and Assignment by Reference?

How Does PHP Handle Array Passing and Assignment by Reference?

Susan Sarandon
Release: 2024-12-10 10:14:20
Original
782 people have browsed it

How Does PHP Handle Array Passing and Assignment by Reference?

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)
Copy after login

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;
}
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template