Home >Backend Development >PHP Problem >Is php array passed by value or reference?

Is php array passed by value or reference?

青灯夜游
青灯夜游Original
2023-01-07 17:23:193394browse

php array is passed by value. PHP array transfer is value transfer; when calling a function, assigning the PHP array as an actual parameter to the formal parameter and modifying it in the function will not affect the array itself, indicating that the transfer in this process is value transfer, and the array variable does not point to A reference to this array itself.

Is php array passed by value or reference?

The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer

php array is passed by value

#Array passing in PHP is by value rather than by reference.

When calling a function, assign the PHP array as an actual parameter to the formal parameter, and modifying it in the function will not affect the array itself.

Explain that the transfer in this process is by value. The array variable is not a reference to the array itself. The PHP array itself exists in the form of a value, and the formal parameter is a copy of the array.

This is very different from other languages ​​​​(such as c, Js, etc.), so it is worth noting!

The example is as follows:

<?php
header("Content-type:text/html;charset=utf-8");
$arr = array(
    'name' => 'corn',
    'age' => '24',
);
var_dump($arr);
test_arr($arr);
function test_arr($arr){
    $arr['name'] = 'qqyumidi';
}
var_dump($arr); 
?>

Is php array passed by value or reference?

You can see that even if the value is reassigned, it will not affect the original array itself.

js code is as follows:

var arr = new Array('corn', '24');
test_arr(arr);
function test_arr(arr){
    arr[0] = 'qqyumidi';
}
console.log(arr);  //result:["qqyumidi", "24"]

Is php array passed by value or reference?

If you need to use the reference transfer effect for value transfer in PHP, you can add the take in front of the formal parameter. Address characters &.

<?php
header("Content-type:text/html;charset=utf-8");
$aa = 100;
echo "原变量值:".$aa; 
test_vars($aa);
function test_vars(&$aa){
    $aa = 200;
}
echo "<br>修好后:".$aa;    //result: 200
?>

Is php array passed by value or reference?

Note:

In PHP, most variable types, such as strings, integers, floating point, arrays etc. are all value types, while classes and objects are reference types. You need to pay attention to this when using them.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Is php array passed by value or 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