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.
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( &#39;name&#39; => &#39;corn&#39;, &#39;age&#39; => &#39;24&#39;, ); var_dump($arr); test_arr($arr); function test_arr($arr){ $arr[&#39;name&#39;] = &#39;qqyumidi&#39;; } var_dump($arr); ?>
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(&#39;corn&#39;, &#39;24&#39;); test_arr(arr); function test_arr(arr){ arr[0] = &#39;qqyumidi&#39;; } console.log(arr); //result:["qqyumidi", "24"]
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 ?>
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!