Home >Backend Development >PHP Tutorial >PHP Arrays: Pass by Value or Pass by Reference?

PHP Arrays: Pass by Value or Pass by Reference?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 21:16:10770browse

PHP Arrays: Pass by Value or Pass by Reference?

Handling Arrays in PHP: Passing by Value or Reference

When working with arrays in PHP, understanding how they are handled when assigned to new variables or passed to functions is crucial.

Array Assignments

When assigning an array to a variable (e.g., $b = $a), PHP always performs a value copy. This means that changes made to the new variable ($b) will not affect the original array ($a), and vice versa. If you need to create a reference to the original array, you must use the reference operator ($b =& $a).

Passing Arrays to Functions

When an array is passed as an argument to a function, it is typically copied by value. This means that modifications made within the function will not modify the original array. To pass an array by reference, the function must be declared with the & symbol before the parameter (e.g., function my_func(& $a)).

Example Code

To illustrate this, consider the following PHP code:

function my_func($a) {
    $a[] = 30;
}

$arr = array(10, 20);
my_func($arr);
var_dump($arr);

Output (Passed by Value):

array
  0 => int 10
  1 => int 20

Output (Passed by Reference):

array
  0 => int 10
  1 => int 20
  2 => int 30

As demonstrated, changes made within the function only affect the array when it is passed by reference.

The above is the detailed content of PHP Arrays: Pass by Value or Pass by Reference?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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